<?php

	/**
	 * Controller für die Bestellungen
	 */
	class wpsg_OrderController extends wpsg_SystemController
	{
		
		/**
		 * Übernimmt die Vertreilung der Anfragen
		 */
		public function dispatch()
		{
			
			parent::dispatch();
			
			if (wpsg_isSizedString($_REQUEST['action'], 'view'))
			{
				$this->viewAction();
			}
			else if (wpsg_isSizedString($_REQUEST['action'], 'switchStatus'))
			{
				$this->switchStatusAction();
			}
			else if (wpsg_isSizedString($_REQUEST['action'], 'setAdminComment'))
			{
				$this->setAdminCommentAction();
			}
			else if (wpsg_isSizedString($_REQUEST['action'], 'storno'))
			{
				$this->stornoAction();
			}
			else if (wpsg_isSizedString($_REQUEST['action'], 'delete'))
			{
				$this->deleteAction();
			}
			else if (wpsg_isSizedString($_REQUEST['action'], 'ajax'))
			{
				$this->ajaxAction();
			}
			else
			{			
				$this->indexAction();
			}
			
		} // public function dispatch()
		
		/**
		 * Setzt den Admin Kommentar
		 */
		public function setAdminCommentAction()
		{
			
			$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
				'admincomment' => wpsg_q($_REQUEST['wpsg_order_admincomment'])
			), "`id` = '".wpsg_q($_REQUEST['edit_id'])."'");				
				
			$this->shop->addBackendMessage(__('Bemerkung wurde erfolgreich gespeichert!', 'wpsg'));
			
			$this->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
			
		} // public function setAdminCommentAction()
		
		/**
		 * Nimmt Ajax Anfragen innerhalb der Bestellverwaltung entgege
		 */
		public function ajaxAction()
		{
			
			if (isset($_REQUEST['mod']))
			{
				
				if (isset($_REQUEST['edit_id']))
				{
					
					$this->shop->view['data'] = $this->db->fetchRow("
						SELECT
							O.*
						FROM
							`".WPSG_TBL_ORDER."` AS O
						WHERE
							O.`id` = '".wpsg_q($_REQUEST['edit_id'])."'					
					");
					
					$this->shop->view['data']['shipping_land'] = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_LAND."` WHERE `id` = '".wpsg_q($this->shop->view['data']['shipping_land'])."'");
					
					$this->shop->view['kunde'] = $this->db->fetchRow("
						SELECT
							K.*
						FROM
							`".WPSG_TBL_KU."` AS K
						WHERE
							K.`id` = '".wpsg_q($this->shop->view['data']['k_id'])."'
					");
					
					$this->shop->view['kunde']['land'] = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_LAND."` WHERE `id` = '".wpsg_q($this->shop->view['kunde']['land'])."'");
 					
				}
				
				$this->shop->callMod($_REQUEST['mod'], 'order_ajax');
				
			}
			else if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'saveInvoiceAdress'))
			{
				
				parse_str($_REQUEST['form_data'], $form_data);
				
				$k_id = $this->db->fetchOne("SELECT `k_id` FROM `".WPSG_TBL_ORDER."` WHERE `id` = '".wpsg_q($_REQUEST['edit_id'])."' ");
				
				$this->db->UpdateQuery(WPSG_TBL_KU, array(
					'firma' => wpsg_q($form_data['dialog_firma']),
					'title' => wpsg_q($form_data['dialog_title']),
					'vname' => wpsg_q($form_data['dialog_vname']),
					'name' => wpsg_q($form_data['dialog_name']),
					'strasse' => wpsg_q($form_data['dialog_strasse']),
					'plz' => wpsg_q($form_data['dialog_plz']),
					'ort' => wpsg_q($form_data['dialog_ort']),
					'land' => wpsg_q($form_data['dialog_land'])
				), " `id` = '".wpsg_q($k_id)."' ");
				
				if (wpsg_isSizedInt($form_data['dialog_shipping']))
				{
					
					$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
						'shipping_firma' => wpsg_q($form_data['dialog_firma']),
						'shipping_title' => wpsg_q($form_data['dialog_title']),
						'shipping_vname' => wpsg_q($form_data['dialog_vname']),
						'shipping_name' => wpsg_q($form_data['dialog_name']),
						'shipping_strasse' => wpsg_q($form_data['dialog_strasse']),
						'shipping_plz' => wpsg_q($form_data['dialog_plz']),
						'shipping_ort' => wpsg_q($form_data['dialog_ort']),
						'shipping_land' => wpsg_q($form_data['dialog_land'])
					), " `id` = '".wpsg_q($_REQUEST['edit_id'])."' ");
					
				}
				
				die("1");
				
			}
			else if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'debug_urlpay'))
			{
			
				$oOrder = wpsg_order::getInstance($_REQUEST['edit_id']);
				$arOrderProducts = $oOrder->getOrderProducts();
				
				foreach ($arOrderProducts as $oOrderProduct)
				{
					
					$oProduct = $oOrderProduct->getProduct();
					
					$this->shop->notifyURL($oProduct->posturl, $oProduct->id, $oOrderProduct->getCount(), $oOrder->id, 1, false, array(
						'product_index' => $oOrderProduct->getProductIndex()
					));
					
				}
				
				$this->shop->addBackendMessage(__('URL Benachrichtigung (Kauf) wurde für die Produkte der Bestellung simuliert.'));
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'debug_urlbuy'))
			{
				
				$oOrder = wpsg_order::getInstance($_REQUEST['edit_id']);
				$arOrderProducts = $oOrder->getOrderProducts();
				
				foreach ($arOrderProducts as $oOrderProduct)
				{
						
					$oProduct = $oOrderProduct->getProduct();
						
					$this->shop->notifyURL($oProduct->posturl, $oProduct->id, $oOrderProduct->getCount(), $oOrder->id, 0, false, array(
							'product_index' => $oOrderProduct->getProductIndex()
					));
						
				}
				
				$this->shop->addBackendMessage(__('URL Benachrichtigung (Bezahlung) wurde für die Produkte der Bestellung simuliert.'));
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'debug_customermail'))
			{
				
				$this->shop->basket->initFromDB($_REQUEST['edit_id']);
				$arBasket = $this->shop->basket->toArray();
				
				$this->shop->basket->sendOrderSaveMails($_REQUEST['edit_id'], $arBasket, true, false, true);
				
				$this->shop->addBackendMessage(wpsg_translate(__('Kundenmail wurde erfolgreich an #1# simuliert.', 'wpsg'), $this->shop->get_option('wpsg_adminmail_empfaenger')));
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'debug_adminmail'))
			{
				
				$this->shop->basket->initFromDB($_REQUEST['edit_id']);
				$arBasket = $this->shop->basket->toArray();
				
				$this->shop->basket->sendOrderSaveMails($_REQUEST['edit_id'], $arBasket, false, true, true);
				
				$this->shop->addBackendMessage(wpsg_translate(__('Adminmail wurde erfolgreich an #1# simuliert.', 'wpsg'), $this->shop->get_option('wpsg_adminmail_empfaenger')));
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
								
			}
			else if ($_REQUEST['wpsg_action'] == 'orderLog')
			{
				
				die($this->orderLogAction($_REQUEST['edit_id']));
				
			}
			
		} // public function ajaxAction()
		
		/**
		 * Ändert den Status einer Bestellung und leitet zur Bestellung zurück
		 */
		public function switchStatusAction()
		{
			
			if (!array_key_exists($_REQUEST['status'], $this->shop->arStatus)) 
			{
				
				$this->shop->addBackendError(__('Status konnte nicht gesetzt werden!', 'wpsg'));
				
			}
			else
			{
			
				$bOK = $this->shop->setOrderStatus($_REQUEST['edit_id'], $_REQUEST['status'], (($_REQUEST['sendMail'] == '1')?true:false));												
				
				if ($bOK)
					$this->shop->addBackendMessage(__('Status wurde erfolgreich geändert!', 'wpsg'));
				else
					$this->shop->addBackendError(__('Status wurde nicht geändert, da unverändert.', 'wpsg'));
				
			}
			
			$this->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
			
		} // public function switchStatusAction()
		
		/**
		 * Wird beim stornieren einer einzelnen Bestellung aufgerufen
		 */
		public function stornoAction()
		{
			
			$this->shop->setOrderStatus($_REQUEST['edit_id'], 500, true);
			$this->shop->addBackendMessage(__('Bestellung wurde storniert und Kunde benachrichtigt.', 'wpsg'));			
			
			$this->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order');
			
		} // public function stornoAction()
		
		/**
		 * Zeichnet das Bestell Log
		 */
		public function orderLogAction($order_id)
		{
			
			$this->shop->view['log'] = $this->db->fetchAssoc("
				SELECT
					OL.*
				FROM
					`".WPSG_TBL_OL."` AS OL
				WHERE
					OL.`o_id` = '".wpsg_q($order_id)."'
				ORDER BY
					OL.`cdate` ASC
			");
			
			return $this->shop->render(WPSG_PATH_VIEW.'/order/orderlog.phtml', false);
			
		} // public function orderLogAction($order_id)
		
		/**
		 * Zeigt eine Bestellung an
		 */
		public function viewAction()
		{
			
			$this->shop->view['data'] = $this->db->fetchRow("
				SELECT
					O.*, K.*,
					O.`id` AS id,
					O.`comment` AS `order_comment`,
					O.`status` AS `status`,
					K.`id` AS k_id,
					L.`kuerzel` AS `land_krzl`,
					L.`name` AS `land_name`
				FROM
					`".WPSG_TBL_ORDER."` AS O 
						LEFT JOIN `".WPSG_TBL_KU."` AS K ON (O.`k_id` = K.`id`)
						LEFT JOIN `".WPSG_TBL_LAND."` AS L ON (K.`land` = L.`id`)
				WHERE
					O.`id` = '".wpsg_q($_REQUEST['edit_id'])."'	
			"); 
			
			$this->shop->view['oOrder'] = wpsg_order::getInstance($_REQUEST['edit_id']);			
			$this->shop->view['orderLog'] = $this->orderLogAction($_REQUEST['edit_id']);
						
			$custom_data = @unserialize($this->shop->view['data']['custom_data']);
			 
			$basket = new wpsg_basket();
			$basket->initFromDB($this->shop->view['data']['id'], true); 
			$this->shop->view['basket'] = $basket->toArray(true);
						
			//wpsg_debug($this->shop->view['basket']);die();
			
			$this->shop->view['colspan'] = 3;
			if ($this->shop->get_option('wpsg_showMwstAlways') == '1' || sizeof($this->shop->view['basket']['mwst']) > 1) $this->shop->view['colspan'] ++;
			
			$this->shop->view['arPayment'] = $this->shop->arPayment;
			$this->shop->view['arShipping'] = $this->shop->arShipping;

			$this->shop->view['country'] = $this->db->fetchRow("
				SELECT
					C.`id`, C.`name`, C.`kuerzel`,
					C.`id` AS `select_key`,
					C.`name` AS `select_value`
				FROM
					`".WPSG_TBL_LAND."` AS C
				WHERE
					C.`id` = '".$this->shop->view['data']['land']."'
			");
			
			$this->shop->view['arCountry'] = $this->db->fetchAssocField("SELECT `id`, `name` FROM `".WPSG_TBL_LAND."` WHERE 1 ", "id", "name");
			
			$this->shop->view['pflicht'] = $this->shop->loadPflichtFeldDaten();
			$this->shop->view['arTitles'] = explode('|', $this->shop->view['pflicht']['anrede_auswahl']);
			
			$this->shop->view['shipping_country'] = $this->db->fetchRow("
				SELECT
					C.`id`, C.`name`, C.`kuerzel`
				FROM
					`".WPSG_TBL_LAND."` AS C
				WHERE
					C.`id` = '".$this->shop->view['data']['shipping_land']."'
			");
			
			$this->shop->render(WPSG_PATH_VIEW.'/order/view.phtml');
			
		} // public function viewAction()
		
		/**
		 * Übernimmt das löschen von Bestellungen
		 */
		public function deleteAction()
		{
			
			if (!isset($_REQUEST['edit_id']))
			{
				
				$this->shop->addBackendError(__('Keine Bestellnummer übergeben.', 'wpsg'));
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order');
				
			}
			
			$this->shop->delOrder($_REQUEST['edit_id']);
			
			$this->shop->addBackendMessage(__('Bestellung erfolgreich gelöscht.', 'wpsg'));
			$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order');
						
		} // public function deleteAction()
		
		public function indexAction()
		{
			
			$strQueryWHERE = '';
			$strQueryStatusWHERE = '';
			$strQueryFROM = '';
			
			if (wpsg_isSizedString($_REQUEST['do'], 'writeMultiRechnung') || wpsg_isSizedString($_REQUEST['wpsg_action'], 'showRechnung'))
			{
				
				// Mehrere Rechnungen schreiben/anzeigen
				if (isset($_REQUEST['ids']))
				{
					
					$IDs = explode("_", $_REQUEST['ids']);
					
				}
				else 
				{
					
					$IDs = array_keys($_REQUEST['wpsg_multido']);
						 
				}
				
				// Hier die Rechnungen noch einmal nach CDATE sortieren
				$IDs = $this->db->fetchAssocField("SELECT `id` FROM `".WPSG_TBL_ORDER."` WHERE `id` IN (".wpsg_q(implode(',', $IDs)).") ORDER BY `cdate` ASC");

				include WPSG_PATH_LIB.'fpdf/fpdf.php';
				include WPSG_PATH_LIB.'fpdf/fpdi.php';
				 
				if (sizeof($IDs) > 0)
				{
					
					$pdf = new FPDI();
					
					foreach ($IDs as $o_id)
					{
						
						$rnr_db = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `rnr` != '' AND `storno` = '0000-00-00 00:00:00' AND `o_id` = '".wpsg_q($o_id)."' ORDER BY `id` DESC");
						$rnr = $rnr_db['rnr'];
						
						$path = $this->shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array($o_id));

						if (file_exists($path.'/R'.$rnr.'.pdf')) $rnr_file = $path.'/R'.$rnr.'.pdf';
						else if (file_exists($path.'/R'.$rnr_db['id'].'.pdf')) $rnr_file = $path.'/R'.$rnr_db['id'].'.pdf';
						else if (file_exists($path.'/'.$rnr_db['id'].'.pdf')) $rnr_file = $path.'/'.$rnr_db['id'].'.pdf';
						else if (file_exists($path.'/'.$rnr_db['rnr'].'.pdf')) $rnr_file = $path.'/'.$rnr_db['rnr'].'.pdf';
						
						if (file_exists($rnr_file))
						{
							
							$pagecount = $pdf->setSourceFile($rnr_file);
							
							for ($i = 1; $i <= $pagecount; $i++) 
							{
							
								$tplidx = $pdf->ImportPage($i);
								$pdf->AddPage();	
								$pdf->useTemplate($tplidx);
							
							}
								
						}
												
					}
					
					die($pdf->Output());
					
				}
				else 
				{
					die(__('Keine Rechnungen gewählt!', 'wpsg'));
				}
				
			}
			
			if (isset($_REQUEST['filter']))
			{

				$this->shop->view['filter'] = $_REQUEST['filter'];
				
			}
			else
			{
				
				$this->shop->view['filter'] = array();
				
				if (isset($_COOKIE['wpsg_order_status']) && !isset($_REQUEST['k_id']))
				{
					
					$this->shop->view['filter']['status'] = $_COOKIE['wpsg_order_status'];
					
				}
				
			}
			
			if (!isset($_REQUEST['k_id']) && !wpsg_isSizedInt($this->shop->view['filter']['status']) && $this->shop->view['filter']['status'] != -1) $this->shop->view['filter']['status'] = 0;
			else if (isset($_REQUEST['k_id']) && !wpsg_isSizedInt($this->shop->view['filter']['status'])) $this->shop->view['filter']['status'] = -1;
			
			if (is_numeric($this->shop->view['filter']['status']) && $this->shop->view['filter']['status'] >= 0)
			{
				
				$strQueryStatusWHERE .= " AND O.`status` = '".wpsg_q($this->shop->view['filter']['status'])."' ";
				
			}
			else if (preg_match('/\d+\,\d+/', $this->shop->view['filter']['status']))
			{

				$strQueryStatusWHERE .= " AND O.`status` IN (".wpsg_q($this->shop->view['filter']['status']).") ";
				
			}
			
			if ($this->shop->view['filter']['k_id'] > 0)
			{
				
				$strQueryWHERE .= " AND O.`k_id` = '".wpsg_q($this->shop->view['filter']['k_id'])."' ";
				
				$this->shop->view['kunde'] = $this->shop->cache->loadKunden($this->shop->view['filter']['k_id']);
				
			}
						
			if (@$this->shop->view['filter']['search'] != '')
			{
				
				$strQueryWHERE .= " 
					AND (
						K.`vname` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' OR
						K.`email` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' OR
						K.`firma` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' OR
						K.`ustidnr` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' OR						
						K.`name` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' OR
						O.`onr` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' OR
						O.`id` = '".wpsg_q($this->shop->view['filter']['search'])."' OR
						O.`custom_data` LIKE '%".wpsg_q($this->shop->view['filter']['search'])."%' 						
					)
				"; 
				
			}
			
			if (@$this->shop->view['filter']['invoice_month_von'] > 0 || @$this->shop->view['filter']['invoice_year_von'] > 0)
			{
				
				$strQueryFROM .= " LEFT JOIN `".WPSG_TBL_RECHNUNGEN."` AS R ON (R.`o_id` = O.`id` AND R.`rnr` != '' AND R.`storno` = '0000-00-00') ";

				if ($this->shop->view['filter']['invoice_month_von'] > 0)
				{
					
					$strQueryWHERE .= " AND DATE_FORMAT(R.`datum`, '%m') = '".wpsg_q($this->shop->view['filter']['invoice_month_von'])."' ";
					
				}
				
				if ($this->shop->view['filter']['invoice_year_von'] > 0)
				{
					
					$strQueryWHERE .= " AND DATE_FORMAT(R.`datum`, '%Y') = '".wpsg_q($this->shop->view['filter']['invoice_year_von'])."' ";
					
				}
				
			}
			
			if (@$this->shop->view['filter']['year_von'] != '' && $this->shop->view['filter']['year_von'] != '-1')
			{
				
				$strQueryWHERE .= " AND DATE_FORMAT(O.`cdate`, '%Y') = '".wpsg_q($this->shop->view['filter']['year_von'])."' ";
				
			}
			
			if (@$this->shop->view['filter']['month_von'] != '' && $this->shop->view['filter']['month_von'] != '-1')
			{
				
				$strQueryWHERE .= " AND DATE_FORMAT(O.`cdate`, '%m') = '".wpsg_q($this->shop->view['filter']['month_von'])."' ";
				
			}
			
			$strQueryORDER = '';
				
			if (!isset($this->shop->view['filter']['order']))
			{
			
				$this->shop->view['filter']['order'] = 'nr';
			
			} 
				
			switch ($this->shop->view['filter']['order'])
			{
			
				case 'customer': $strQueryORDER = " K.`name` "; break;
				case 'payment': $strQueryORDER = " `payment_name` "; break;			
				case 'produkte': $strQueryORDER = " `produkt_menge` "; break;
				case 'amount': $strQueryORDER = " O.`price_gesamt` "; break;
				case 'status': $strQueryORDER = " `status_name` "; break;				
				case 'abo': $strQueryORDER = " `abo` "; break;
				default: $strQueryORDER = " O.`cdate` "; break;
			
			}
							
			if (!isset($this->shop->view['filter']['ascdesc']))
			{
			
				$this->shop->view['filter']['ascdesc'] = 'DESC';
			
			}
			
			$nPerPage = $this->get_option('wpsg_order_perpage');
			if ($nPerPage <= 0) $nPerPage = 10;
			
			if (isset($_REQUEST['seite'])) $seite = $_REQUEST['seite']; else $seite = 1;
				
			// Bestellungen nach Status zählen
			$this->shop->view['arStatus'] = array();
			foreach ((array)$this->shop->arStatus as $status_id => $status)
			{
					
				$count = $this->db->fetchOne("
					SELECT
						COUNT(*)
					FROM
						`".WPSG_TBL_ORDER."` AS O
							LEFT JOIN `".WPSG_TBL_KU."` AS K ON (K.`id` = O.`k_id`)
							".$strQueryFROM."
					WHERE
						1
						".$strQueryWHERE."
						AND O.`status` = '".wpsg_q($status_id)."'
				");
							
				$this->shop->view['arStatus'][$status_id] = $count;
					
				if ($this->shop->get_option('wpsg_showincompleteorder') != '1' && $status_id == wpsg_ShopController::STATUS_UNVOLLSTAENDIG) unset($this->shop->view['arStatus'][$status_id]);
				
			}
							
			//if (!isset($this->shop->view['filter']['status']) || !array_key_exists($this->shop->view['filter']['status'], $this->shop->view['arStatus'])) $this->shop->view['filter']['status'] = '-1';
			
			//if (wpsg_isSizedString($this->shop->view['filter']['status']))
			//{
			 
			if (is_numeric($this->shop->view['filter']['status']) && $this->shop->view['filter']['status'] >= 0)
			{
			
				$strQueryStatusWHERE .= " AND O.`status` = '".wpsg_q($this->shop->view['filter']['status'])."' ";
				
			}
			else if (preg_match('/\d+\,\d+/', $this->shop->view['filter']['status']))
			{
				
				$strQueryStatusWHERE .= " AND O.`status` IN (".wpsg_q($this->shop->view['filter']['status']).") ";
				
			}					
			else if (wpsg_isSizedString($this->shop->view['filter']['status'], '-1'))
			{
				
				$strQueryStatusWHERE .= " AND O.`status` != '".wpsg_q(wpsg_ShopController::STATUS_UNVOLLSTAENDIG)."' ";
				
			}
			
			//}
			
			$this->shop->view['count'] = $this->db->fetchOne("
				SELECT
					COUNT(*)
				FROM	
					`".WPSG_TBL_ORDER."` AS O
						LEFT JOIN `".WPSG_TBL_KU."` AS K ON (K.`id` = O.`k_id`)
						".$strQueryFROM."
				WHERE 
					1
					".$strQueryWHERE."
					".$strQueryStatusWHERE."
			");
			
			$this->shop->view['countAll'] = $this->db->fetchOne("
				SELECT
					COUNT(*)
				FROM
					`".WPSG_TBL_ORDER."` AS O
						LEFT JOIN `".WPSG_TBL_KU."` AS K ON (K.`id` = O.`k_id`)
						".$strQueryFROM."
				WHERE
					1
					".$strQueryWHERE."
			");
			 		
			$this->shop->view['seite'] = $seite;
			$this->shop->view['pages'] = ceil($this->shop->view['count'] / $nPerPage); 			
			if ($this->shop->view['seite'] <= 0 || $this->shop->view['seite'] > $this->shop->view['pages']) $this->shop->view['seite'] = 1;

			// Beim Export Pager ignorieren
			if (!wpsg_isSizedInt($_REQUEST['submit_export']))
			{

				$strQueryLIMIT .= "
					LIMIT
						".(($this->shop->view['seite'] - 1) * $nPerPage).", ".$nPerPage."
				";
				
			}

			$strQuerySELECT = "";
			if (sizeof($this->shop->arPayment) >= 1 && $this->shop->view['filter']['order'] == 'payment') 
			{
			
				$strQuerySELECT .= " (CASE O.`type_payment` ";				
				foreach ($this->shop->arPayment as $p) { $strQuerySELECT .= " WHEN '".wpsg_q($p['id'])."' THEN '".wpsg_q($p['name'])."' "; }
				$strQuerySELECT .= " END) AS `payment_name`, ";
						
			}
			 
			if (sizeof($this->shop->arShipping) >= 1 && $this->shop->view['filter']['order'] == 'shipping')
			{
					
				$strQuerySELECT .= " (CASE O.`type_shipping` ";
				foreach ($this->shop->arShipping as $s) { $strQuerySELECT .= " WHEN '".wpsg_q($s['id'])."' THEN '".wpsg_q($s['name'])."' "; }
				$strQuerySELECT .= " END) AS `payment_name`, ";
			
			}
			
			if ($this->shop->view['filter']['order'] == 'abo')
			{
				
				$strQuerySELECT  = " (
					IF (
						O.`wpsg_mod_abo_origin_order` > 0,
						(SELECT ABO.`cdate` FROM `".WPSG_TBL_ABO."` AS ABO WHERE `order_id` = O.`wpsg_mod_abo_origin_order`),
						(SELECT ABO.`cdate` FROM `".WPSG_TBL_ABO."` AS ABO WHERE `order_id` = O.`id`)  
					)		 
				) AS `abo`, ";
				
			}
			
			if ($this->shop->view['filter']['order'] == 'produkte')
			{
				
				$strQuerySELECT .= " (SELECT SUM(OP.`menge`) FROM `".WPSG_TBL_ORDERPRODUCT."` AS OP WHERE OP.`o_id` = O.`id`) AS `produkt_menge`, ";
				
			}
			
			if ($this->shop->view['filter']['order'] == 'status')
			{
				
				$strQuerySELECT .= " (CASE O.`status` ";
				foreach ($this->shop->arStatus as $s_id => $s) { $strQuerySELECT .= " WHEN '".wpsg_q($s_id)."' THEN '".wpsg_q($s)."' "; }
				$strQuerySELECT .= " END) AS `status_name`, ";
				
			}
						
			$strQuery = "
				SELECT
					O.*, K.*,
					".$strQuerySELECT."
					O.`status` AS `status`, 
					O.`comment` AS `order_comment`, 
					O.`id` AS id
				FROM	
					`".WPSG_TBL_ORDER."` AS O
						LEFT JOIN `".WPSG_TBL_KU."` AS K ON (K.`id` = O.`k_id`)
						".$strQueryFROM."
				WHERE
					1 
					".$strQueryWHERE."
					".$strQueryStatusWHERE."
				ORDER BY					
					".wpsg_q($strQueryORDER)." ".wpsg_q($this->shop->view['filter']['ascdesc']).", O.`cdate` DESC 
					".$strQueryLIMIT."				
			"; 
			 
			$this->shop->view['data'] = $this->db->fetchAssoc($strQuery); 	
			
			if (isset($_REQUEST['wpsg_action']))
			{
				
				if ($_REQUEST['wpsg_action'] == '-1')
				{
					$this->addBackendError(__('Bitte eine Aktion wählen!', 'wpsg'));
				}
				else if (!isset($_REQUEST['wpsg_multido']) || !is_array($_REQUEST['wpsg_multido']))
				{
					$this->addBackendError(__('Bitte mindestens eine Bestellung auswählen!', 'wpsg'));
				}
				else 
				{
					
					if ($_REQUEST['wpsg_action'] == 'multiDelete')
					{
						
						// Sortieren nach CDDATE
						$arIDs_write = $this->db->fetchAssocField("SELECT `id` FROM `".WPSG_TBL_ORDER."` WHERE `id` IN (".wpsg_q(implode(',', array_keys($_REQUEST['wpsg_multido']))).") ORDER BY `cdate` ASC");
						
						// Rechnung für mehrere Bestellungen schreiben
						foreach ($arIDs_write as $k)
						{
							
							$this->shop->delOrder($k);
							
						}
						
						$this->shop->addBackendError(wpsg_translate(__('#1# Bestellung(en) gelöscht.', 'wpsg'), sizeof($arIDs_write)));
						
					}
					else if ($_REQUEST['wpsg_action'] == 'writeRechnung')
					{
						
						$nWriteRechnung = 0;
						
						// E-Mail an Kunden senden
						$_REQUEST['wpsg_rechnungen_sendmail'] = '1';
						
						// Rechnungsdatum
						$_REQUEST['wpsg_rechnungen_datum'] = date('d.m.Y');
						
						// Status setzen
						$_REQUEST['wpsg_rechnungen_status'] = '1';
						
						// Neuer Status 
						$_REQUEST['wpsg_rechnungen_status_neu'] = '110';
						
						// Fußtext
						if ($this->shop->get_option('wpsg_rechnungen_foottext_standard') !== false)
						{
							
							$wpsg_rechnungen_footer = $this->get_option("wpsg_rechnungen_footer");
 							if (!is_array($wpsg_rechnungen_footer)) $wpsg_rechnungen_footer = unserialize($this->get_option("wpsg_rechnungen_footer"));
							if (!is_array($wpsg_rechnungen_footer)) $wpsg_rechnungen_footer = Array();
							
							$_REQUEST['wpsg_rechnungen_fusstext'] = $wpsg_rechnungen_footer[$this->shop->get_option('wpsg_rechnungen_foottext_standard')][1];

						}
						else
						{
							
							$_REQUEST['wpsg_rechnungen_fusstext'] = '';
							
						}
												
						// URL Benachrichtigung
						$_REQUEST['wpsg_rechnungen_url'] = '0';
						
						// Fälligkeit anzeigen
						$_REQUEST['wpsg_rechnungen_faelligkeit'] = '1';
						
						$arIDs = array();
						
						// Sortieren nach CDDATE
						$arIDs_write = $this->db->fetchAssocField("SELECT `id` FROM `".WPSG_TBL_ORDER."` WHERE `id` IN (".wpsg_q(implode(',', array_keys($_REQUEST['wpsg_multido']))).") ORDER BY `cdate` ASC");
						
						// Rechnung für mehrere Bestellungen schreiben
						foreach ($arIDs_write as $k)
						{

							$bRechnungExists = $this->db->fetchOne("SELECT COUNT(*) FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `rnr` != '' AND `o_id` = '".wpsg_q($k)."' AND `storno` = '0000-00-00 00:00:00'");

							// E-Mail aus Bestellung
							$_REQUEST['wpsg_rechnungen_email'] = $this->db->fetchOne("SELECT K.`email` FROM `".WPSG_TBL_ORDER."` AS O LEFT JOIN `".WPSG_TBL_KU."` AS K ON (O.`k_id` = K.`id`) WHERE O.`id` = '".wpsg_q($k)."'");
							
							if ($bRechnungExists <= 0)
							{
							
								$this->shop->callMod('wpsg_mod_rechnungen', 'writeRechnung', array($k, false, false));
								$arIDs[] = $k;
								$nWriteRechnung ++;
								
							}
														
						}
						
						if ($nWriteRechnung <= 0)
						{
							
							$this->addBackendError(__('Für die gewählten Bestellungen konnten keine Rechnungen geschrieben werden, bestehende Rechnungen müssen erst storniert werden.', 'wpsg'));
							
						}
						else 
						{
							
							$this->addBackendMessage(
								'nohspc_'.
								wpsg_translate(__('#1# Rechnungen geschrieben', 'wpsg'), $nWriteRechnung).
								' <a href="'.WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&noheader=1&do=writeMultiRechnung&ids='.implode('_', $arIDs).'" target="_new">'.__('Download', 'wpsg').'</a>'
							);
							
						}
						
					}
					else if (is_numeric($_REQUEST['wpsg_action']))
					{
						
						// Status setzen						
						foreach ($_REQUEST['wpsg_multido'] as $k => $v)
						{
							
							$this->shop->setOrderStatus($k, $_REQUEST['wpsg_action'], false);
							
						}
						
						$this->addBackendMessage(wpsg_translate(__('Status von #1# Bestellungen aktualisiert (Kunden wurden nicht benachrichtigt)', 'wpsg'), sizeof($_REQUEST['wpsg_multido'])));
						
					}
										
				}
				
				$requestString = http_build_query(array("filter" => $_REQUEST['filter']), null, '&');					
				if ($_REQUEST['seite'] > 0) $requestString .= "&seite=".$_REQUEST['seite'];
				
				$this->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order'.$requestString);
				
			}
			
			foreach ($this->shop->view['data'] as $k => $v)
			{
				
				$basket = new wpsg_basket();
				$basket->initFromDB($v['id'], true);
				$this->shop->view['data'][$k]['basket'] = $basket->toArray(true);

				// Bestellobjekt
				$this->shop->view['data'][$k]['oOrder'] = wpsg_order::getInstance($v['id']);
				
				if ($v['shipping_land'] > 0) $this->shop->view['data'][$k]['land_krzl'] = $this->db->fetchOne("SELECT L.`kuerzel` FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($v['shipping_land'])."' ");
				else if ($v['land'] > 0) $this->shop->view['data'][$k]['land_krzl'] = $this->db->fetchOne("SELECT L.`kuerzel` FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($v['land'])."' ");
				else $this->shop->view['data'][$k]['land_krzl'] = '12';
				
			}
			
			$this->shop->view['years'] = $this->db->fetchAssocField("SELECT DISTINCT DATE_FORMAT(`cdate`, '%Y') FROM `".WPSG_TBL_ORDER."`");
									
			if ($this->shop->hasMod('wpsg_mod_rechnungen'))
			{
				
				$this->shop->view['invoice_years'] = $this->db->fetchAssocField("SELECT DISTINCT DATE_FORMAT(`datum`, '%Y') FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `storno` = '0000-00-00' AND `gnr` = '' ");
				
			}
			
			if (isset($_REQUEST['submit_export']) && $_REQUEST['submit_export'] == '1')
			{
				
				$this->shop->callMod('wpsg_mod_export', 'handleExport');
				
			}
			else
			{
				
				$this->shop->render(WPSG_PATH_VIEW.'/order/index.phtml');
			
			}
			
		} // public function indexAction()
		
	} // class wpsg_OrderController extends wpsg_SystemController

?>