<?php
/**
 * Order export class
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Export
 * @author 		Roland Dalmulder
 * @link 		http://www.csvimproved.com
 * @copyright 	Copyright (C) 2006 - 2012 RolandD Cyber Produksi
 * @license 	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * @version 	$Id: orderexport.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );
 
/**
 * Processor for order exports
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Export
 */
class CsvivirtuemartModelOrderExport extends CsvivirtuemartModelExportfile {
	
	/**
	 * Order export
	 *
	 * Exports order details
	 * 
	 * @copyright 
	 * @author 		RolandD
	 * @todo 
	 * @see 
	 * @access 		public
	 * @param 
	 * @return 		void
	 * @since 		3.0
	 */
	public function getStart() {
		
		// Get some basic data
		$db = JFactory::getDBO();
		$csvidb = new CsviDb();
		$csvilog = JRequest::getVar('csvilog');
		$template = JRequest::getVar('template');
		$exportclass =  JRequest::getVar('export.class');
		$export_fields = JRequest::getVar('export.fields');
		$config = JFactory::getConfig();
		$secret =  md5($config->getValue('config.secret'));
		$address = strtoupper($template->getValue('order_address', 'order', false));
		if ($address == 'BTST') $user_info_fields = CsvivirtuemartModelAvailablefields::DbFields('vm_order_user_info');
		else $user_info_fields = array();
		
		// Build something fancy to only get the fieldnames the user wants
		$userfields = array();
		foreach ($export_fields as $column_id => $field) {
			switch ($field->field_name) {
				case 'order_id':
					$userfields[] = '#__vm_orders.order_id';
					break;
				case 'user_id':
					$userfields[] = '#__vm_orders.user_id';
					break;
				case 'order_date':
					$userfields[] = '#__vm_orders.cdate AS order_date';
					break;
				case 'order_modified_date':
					$userfields[] = '#__vm_orders.mdate AS order_modified_date';
					break;
				case 'payment_method_id':
					$userfields[] = '#__vm_payment_method.payment_method_id';
					break;
				case 'product_sku':
					$userfields[] = 'order_item_sku AS product_sku';
					break;
				case 'product_name':
					$userfields[] = 'order_item_name AS product_name';
					break;
				case 'product_item_price':
					$userfields[] = 'product_item_price AS product_price';
					break;
				case 'manufacturer_id':
					$userfields[] = '#__vm_manufacturer.manufacturer_id';
					break;
				case 'manufacturer_category_id':
					$userfields[] = 'mf_category_id AS manufacturer_category_id';
					break;
				case 'manufacturer_desc':
					$userfields[] = 'mf_desc AS manufacturer_desc';
					break;
				case 'manufacturer_email':
					$userfields[] = 'mf_email AS manufacturer_email';
					break;
				case 'manufacturer_name':
					$userfields[] = 'mf_name AS manufacturer_name';
					break;
				case 'manufacturer_url':
					$userfields[] = 'mf_url AS manufacturer_url';
					break;
				case 'product_id':
					$userfields[] = '#__vm_order_item.product_id';
					break;
				case 'order_status':
					$userfields[] = '#__vm_orders.order_status';
					break;
				case 'list_order':
					$userfields[] = '#__vm_order_status.list_order';
					break;
				case 'product_price':
					$userfields[] = '#__vm_order_item.product_item_price';
					break;
				case 'order_payment_number':
					$userfields[] = 'AES_DECRYPT(order_payment_number,'.$db->Quote($secret).') AS order_payment_number';
					break;
				case 'cdate':
					$userfields[] = '#__vm_orders.cdate';
					break;
				case 'mdate':
					$userfields[] = '#__vm_orders.mdate';
					break;
				case 'full_name':
					if (!$this->searchExportFields('first_name')) $userfields[] = 'user_info1.first_name';
					if (!$this->searchExportFields('middle_name')) $userfields[] = 'user_info1.middle_name';
					if (!$this->searchExportFields('last_name')) $userfields[] = 'user_info1.last_name';
					break;
				case 'product_price_total':
					$userfields[] = 'product_item_price*product_quantity AS product_price_total';
					break;
				case 'discount_percentage':
					$userfields[] = '(order_discount/order_total)*100 AS discount_percentage';
					break;
				case 'user_info_id':
					$userfields[] = '#__vm_orders.user_info_id';
					break;
				case 'vendor_id':
					$userfields[] = '#__vm_orders.vendor_id';
					break;
				case 'custom':
				case 'total_order_items':
					// These are man made fields, do not try to get them from the database
					break;
				default:
					if ($address == 'BTST' && array_key_exists($field->field_name, $user_info_fields)) {
						$userfields[] = 'COALESCE(user_info2.'.$field->field_name.', user_info1.'.$field->field_name.') AS '.$field->field_name;
					}
					else $userfields[] = $field->field_name;
					break;
			}
		}
		
		// Construct the query
		$q = "SELECT ".implode(",", $userfields);
		$q .= " FROM #__vm_orders
			LEFT JOIN #__vm_order_item
			ON #__vm_orders.order_id = #__vm_order_item.order_id
			LEFT JOIN #__vm_order_user_info AS user_info1
			ON #__vm_orders.order_id = user_info1.order_id";
		if ($address == 'BTST') $q .= " LEFT JOIN #__vm_order_user_info AS user_info2
			ON #__vm_orders.order_id = user_info2.order_id
			AND user_info2.address_type = 'ST'";
		$q .= " LEFT JOIN #__vm_order_payment
			ON #__vm_orders.order_id = #__vm_order_payment.order_id
			LEFT JOIN #__vm_payment_method
			ON #__vm_order_payment.payment_method_id = #__vm_payment_method.payment_method_id
			LEFT JOIN #__vm_order_status
			ON #__vm_orders.order_status = #__vm_order_status.order_status_code
			LEFT JOIN  #__vm_product_mf_xref
			ON #__vm_order_item.product_id = #__vm_product_mf_xref.product_id
			LEFT JOIN #__vm_manufacturer
			ON #__vm_product_mf_xref.manufacturer_id = #__vm_manufacturer.manufacturer_id
			LEFT JOIN #__users
			ON #__users.id = user_info1.user_id
			LEFT JOIN #__vm_country
			ON #__vm_country.country_3_code = user_info1.country
			";
			
		// Check if there are any selectors
		$selectors = array();
		
		// Filter by manufacturer
		$manufacturer = $template->getValue('manufacturer', 'order', false);
		if ($manufacturer && $manufacturer[0] != 'none') {
			$selectors[] = '#__vm_manufacturer.manufacturer_id IN ('.implode(',', $manufacturer).')';
		}
		
		// Filter by order number start
		$ordernostart = $template->getValue('ordernostart', 'order', array(), 'int');
		if ($ordernostart > 0) {                
			$selectors[] = '#__vm_orders.order_id >= '.$ordernostart;
		}
		
		// Filter by order number end
		$ordernoend = $template->getValue('ordernoend', 'order', array(), 'int');
		if ($ordernoend > 0) {                
			$selectors[] = '#__vm_orders.order_id <= '.$ordernoend;
		}
		
		// Filter by list of order numbers
		$orderlist = $template->getValue('orderlist', 'order');
		if ($orderlist) {                
			$selectors[] = '#__vm_orders.order_id IN ('.$orderlist.')';
		}
		
		// Filter by order date start
		$orderdatestart = $template->getValue('orderdatestart', 'order', false);
		if ($orderdatestart) {
			$orderdate = JFactory::getDate($orderdatestart);
			$selectors[] = '#__vm_orders.cdate >= '.$db->Quote($orderdate->toUnix());
		}
		
		// Filter by order date end
		$orderdateend = $template->getValue('orderdateend', 'order', false);
		if ($orderdateend) {
			$orderdate = JFactory::getDate($orderdateend);
			$selectors[] = '#__vm_orders.cdate <= '.$db->Quote($orderdate->toUnix());
		}
		
		// Filter by order modified date start
		$ordermdatestart = $template->getValue('ordermdatestart', 'order', false);
		if ($ordermdatestart) {
			$ordermdate = JFactory::getDate($ordermdatestart);
			$selectors[] = '#__vm_orders.mdate >= '.$db->Quote($ordermdate->toUnix());
		}
		
		// Filter by order modified date end
		$ordermdateend = $template->getValue('ordermdateend', 'order', false);
		if ($ordermdateend) {
			$ordermdate = JFactory::getDate($ordermdateend);
			$selectors[] = '#__vm_orders.mdate <= '.$db->Quote($ordermdate->toUnix());
		}
		
		// Filter by order status
		$orderstatus = $template->getValue('orderstatus', 'order', false);
		if ($orderstatus && $orderstatus[0] != '') {
			$selectors[] = '#__vm_orders.order_status IN (\''.implode("','", $orderstatus).'\')';
		}
		
		// Filter by order price start
		$pricestart = $template->getValue('orderpricestart', 'order', false, 'float');
		if ($pricestart) {                
			$selectors[] = '#__vm_orders.order_total >= '.$pricestart;
		}
		
		// Filter by order price end
		$priceend = $template->getValue('orderpriceend', 'order', false, 'float');
		if ($priceend) {                
			$selectors[] = '#__vm_orders.order_total <= '.$priceend;
		}
		
		// Filter by order user id
		$orderuser = $template->getValue('orderuser', 'order', false);
		if ($orderuser && $orderuser[0] != '') {
			$selectors[] = '#__vm_orders.user_id IN (\''.implode("','", $orderuser).'\')';
		}
		
		// Filter by order product
		$orderproduct = $template->getValue('orderproduct', 'order', false);
		if ($orderproduct && $orderproduct[0] != '') {
			$selectors[] = '#__vm_order_item.order_item_sku IN (\''.implode("','", $orderproduct).'\')';
		}
		
		// Filter by address type
		if ($address) {
			switch (strtoupper($address)) {
				case 'BTST':
					$selectors[] = "user_info1.address_type = 'BT'";
					break;
				default:
					$selectors[] = 'user_info1.address_type = '.$db->Quote(strtoupper($address));
					break;
			}
		}
		
		// Filter by order currency
		$ordercurrency = $template->getValue('ordercurrency', 'order', false);
		if ($ordercurrency && $ordercurrency[0] != '') {
			$selectors[] = '#__vm_orders.order_currency IN (\''.implode("','", $ordercurrency).'\')';
		}
		
		// Filter by payment method
		$orderpayment = $template->getValue('orderpayment', 'order', false);
		if ($orderpayment && $orderpayment[0] != '') {
			$selectors[] = '#__vm_order_payment.payment_method_id IN (\''.implode("','", $orderpayment).'\')';
		}
		
		// Check if we need to attach any selectors to the query
		if (count($selectors) > 0 ) $q .= ' WHERE '.implode(' AND ', $selectors)."\n";
		
		// Check if we need to group the orders together
		$groupby = $template->getValue('groupby', 'general', false, 'bool');
		if ($groupby) $q .= $this->getFilterBy('groupby', $address, $user_info_fields); 
		
		// Order by set field
		$q .= $this->getFilterBy('sort', $address, $user_info_fields);
		
		// Add a limit if user wants us to
		$q .= $this->getExportLimit();
		
		// Execute the query
		$csvidb->setQuery($q);
		$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_EXPORT_QUERY'), true);
		// There are no records, write SQL query to log
		if ($csvidb->getErrorNum() > 0) {
			$this->addExportContent(JText::sprintf('COM_CSVIVIRTUEMART_ERROR_RETRIEVING_DATA', $csvidb->getErrorMsg()));
			$this->writeOutput();
			$csvilog->AddStats('incorrect', $csvidb->getErrorMsg());
		}
		else {
			$logcount = $csvidb->getNumRows();
			JRequest::setVar('logcount', array('export' => $logcount));
			if ($logcount > 0) {
				while ($record = $csvidb->getRow()) {
					if ($template->getValue('export_file', 'general') == 'xml' || $template->getValue('export_file', 'general') == 'html') $this->addExportContent($exportclass->NodeStart());
					foreach ($export_fields as $column_id => $field) {
						if ($field->process) {
							$fieldname = $field->field_name;
							$fieldreplace = $field->field_name.$field->column_header;
							// Add the replacement
							if (isset($record->$fieldname)) $fieldvalue = CsviHelper::replaceValue($fieldreplace, $record->$fieldname);
							else $fieldvalue = '';
							switch ($fieldname) {
								case 'order_date':
								case 'order_modified_date':
								case 'order_payment_expire':
								case 'cdate':
								case 'mdate':
									$$fieldname = trim($record->$fieldname);
									if (strlen($$fieldname) == 0 || $$fieldname == 0) {
										// Check if we have a default value
										if (strlen(trim($field->default_value)) > 0) {
											$$fieldname = $field->default_value;
										}
										else $$fieldname = '';
									}
									else {
										$$fieldname = date($template->getValue('export_date_format', 'general'), $$fieldname);
									}
									$$fieldname = CsviHelper::replaceValue($fieldreplace, $$fieldname);
									$this->addExportField($field->combine, $$fieldname, $fieldname, $field->column_header);
									break;
								case 'address_type':
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									if ($fieldvalue == 'BT') $fieldvalue = JText::_('COM_CSVIVIRTUEMART_BILLING_ADDRESS');
									else if ($fieldvalue == 'ST') $fieldvalue = JText::_('COM_CSVIVIRTUEMART_SHIPPING_ADDRESS');
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								case 'full_name':
									$fieldvalue = str_replace('  ', ' ', $record->first_name.' '.$record->middle_name.' '.$record->last_name);
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								case 'order_id':
									// Let's see if the user wants us to get a total number of items
									if ($this->searchExportFields('total_order_items')) {
										// Let's calculate total order items
										$db = JFactory::getDBO();
										$q = "SELECT COUNT(order_id) AS totalitems
											FROM #__vm_order_item
											WHERE order_id = ".$fieldvalue;
										$db->setQuery($q);
										JRequest::setVar('total_order_items', $db->loadResult());
									}
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								case 'total_order_items':
									$fieldvalue = JRequest::getVar('total_order_items', '');
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								case 'custom':
									// Has no database value, get the default value only
									$fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								case 'product_price':
									$fieldvalue =  number_format($record->product_item_price, $template->getValue('export_price_format_decimal', 'general', 2, 'int'), $template->getValue('export_price_format_decsep', 'general'), $template->getValue('export_price_format_thousep', 'general'));
									$fieldvalue = CsviHelper::replaceValue($fieldreplace, $fieldvalue);
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								case 'order_tax':
								case 'order_total':
								case 'order_subtotal':
								case 'order_shipping':
								case 'order_shipping_tax':
								case 'coupon_discount':
								case 'order_discount':
									$fieldvalue =  number_format($fieldvalue, $template->getValue('export_price_format_decimal', 'general', 2, 'int'), $template->getValue('export_price_format_decsep', 'general'), $template->getValue('export_price_format_thousep', 'general'));
									$fieldvalue = CsviHelper::replaceValue($fieldreplace, $fieldvalue);
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
								default:
									// Check if we have any content otherwise use the default value
									if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
									$this->addExportField($field->combine, $fieldvalue, $fieldname, $field->column_header);
									break;
							}
						}
					}
					
					// Clean the totalitems
					JRequest::setVar('total_order_items', 0);
					
					if ($template->getValue('export_file', 'general') == 'xml' || $template->getValue('export_file', 'general') == 'html') {
						$this->addExportContent($exportclass->NodeEnd());
					}
					
					// Output the contents
					$this->writeOutput();
				}
			}
			else {
				$this->addExportContent(JText::_('COM_CSVIVIRTUEMART_NO_DATA_FOUND'));
				// Output the contents
				$this->writeOutput();
			}
		}
	}
	
	/**
	 * Create an SQL filter 
	 * 
	 * @copyright 
	 * @author 		RolandD
	 * @todo 
	 * @see 
	 * @access 		protected
	 * @param 		string	$filter	what kind of SQL type should be created
	 * @return 		string	the SQL part to add to the query
	 * @since 		3.0
	 */
	protected function getFilterBy($filter, $address, $user_info_fields) {
		$db = JFactory::getDBO();
		$export_fields = JRequest::getVar('export.fields');
		$fields = array();
		
		foreach ($export_fields as $column_id => $field) {
			switch ($filter) {
				case 'groupby':
					$process = true;
					break;
				case 'sort':
					$process = $field->sort;
					break;
				default:
					$process = false;
			}
			if ($process) {
				switch ($field->field_name) {
					case 'custom':
					case 'total_order_items':
					case 'discount_percentage':
					case 'product_price_total':
					case 'full_name':
						break;
					case 'product_price':
						$fields[] = $db->nameQuote('product_item_price');
						break;
					case 'payment_method_id':
						$fields[] = $db->nameQuote('#__vm_order_payment').'.'.$db->nameQuote('payment_method_id');
						break;
					case 'list_order':
						$fields[] = $db->nameQuote('#__vm_order_status').'.'.$db->nameQuote('list_order');
						break;
					case 'manufacturer_category_id':
						$fields[] = $db->nameQuote('#__vm_manufacturer').'.'.$db->nameQuote('mf_category_id');
						break;
					case 'manufacturer_desc':
						$fields[] = $db->nameQuote('#__vm_manufacturer').'.'.$db->nameQuote('mf_desc');
						break;
					case 'manufacturer_email':
						$fields[] = $db->nameQuote('#__vm_manufacturer').'.'.$db->nameQuote('mf_email');
						break;
					case 'manufacturer_name':
						$fields[] = $db->nameQuote('#__vm_manufacturer').'.'.$db->nameQuote('mf_name');
						break;
					case 'manufacturer_url':
						$fields[] = $db->nameQuote('#__vm_manufacturer').'.'.$db->nameQuote('mf_url');
						break;
					default:
						if ($address == 'BTST' && array_key_exists($field->field_name, $user_info_fields)) $fields[] = $db->nameQuote('user_info1').'.'.$db->nameQuote($field->field_name);
						else $fields[] = $db->nameQuote($field->field_name);
						break;
				}
			}
		}
		
		// Construct the SQL part
		if (!empty($fields)) {
			switch ($filter) {
				case 'groupby':
					$groupby_fields = array_unique($fields);
					$q = " GROUP BY ".implode(',', $groupby_fields);
					break;
				case 'sort':
					$sort_fields = array_unique($fields);
					$q = " ORDER BY ".implode(', ', $sort_fields);
					break;
				default:
					$q = '';
					break;
			}
		}
		else $q = '';
		
		return $q;
	}
}
?>