<?php
/**
 * Order items 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: orderitemexport.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );
 
/**
 * Processor for order items exports
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Export
 */
class CsvivirtuemartModelOrderitemExport extends CsvivirtuemartModelExportfile {
	
	/**
	 * Order items export
	 *
	 * Exports order items data to either csv, xml or HTML format 
	 * 
	 * @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');
		
		// 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 'product_price':
					$userfields[] = 'product_item_price AS product_price';
					break;
				case 'product_sku':
					$userfields[] = 'order_item_sku AS product_sku';
					break;
				case 'product_name':
					$userfields[] = 'order_item_name AS product_name';
					break;
				case 'full_name':
					$userfields[] = 'user_info1.first_name';
					$userfields[] = 'user_info1.middle_name';
					$userfields[] = 'user_info1.last_name';
					break;
				case 'cdate':
				case 'mdate':
				case 'order_id':
				case 'order_status':
				case 'user_info_id':
				case 'vendor_id':
					$userfields[] = '#__vm_order_item.'.$field->field_name;
					break;
				default:
					$userfields[] = $field->field_name;
					break;
			}
		}
		
		// Construct the query
		$q = "SELECT ".implode(",", $userfields);
		$q .= " FROM #__vm_order_item
			LEFT JOIN #__vm_orders
			ON #__vm_orders.order_id = #__vm_order_item.order_id
			LEFT JOIN #__vm_order_user_info AS user_info1
			ON #__vm_order_item.order_id = user_info1.order_id
			LEFT JOIN #__vm_order_status
			ON #__vm_order_item.order_status = #__vm_order_status.order_status_code";
		
		// Check if there are any selectors
		$selectors = array();
		
		// Filter by order number start
		$ordernostart = $template->getValue('orderitemsnostart', 'orderitem', array(), 'int');
		if ($ordernostart > 0) {                
			$selectors[] = '#__vm_order_item.order_id >= '.$ordernostart;
		}
		
		// Filter by order number end
		$ordernoend = $template->getValue('orderitemsnoend', 'orderitem', array(), 'int');
		if ($ordernoend > 0) {                
			$selectors[] = '#__vm_order_item.order_id <= '.$ordernoend;
		}
		
		// Filter by list of order numbers
		$orderlist = $template->getValue('orderitemslist', 'orderitem');
		if ($orderlist) {                
			$selectors[] = '#__vm_order_item.order_id IN ('.$orderlist.')';
		}
		
		// Filter by order date start
		$orderdatestart = $template->getValue('orderitemsdatestart', 'orderitem', false);
		if ($orderdatestart) {
			$orderdate = JFactory::getDate($orderdatestart);
			$selectors[] = '#__vm_order_item.cdate >= '.$db->Quote($orderdate->toUnix());
		}
		
		// Filter by order date end
		$orderdateend = $template->getValue('orderitemsdateend', 'orderitem', false);
		if ($orderdateend) {
			$orderdate = JFactory::getDate($orderdateend);
			$selectors[] = '#__vm_order_item.cdate <= '.$db->Quote($orderdate->toUnix());
		}
		
		// Filter by order modified date start
		$ordermdatestart = $template->getValue('orderitemsmdatestart', 'orderitem', false);
		if ($ordermdatestart) {
			$ordermdate = JFactory::getDate($ordermdatestart);
			$selectors[] = '#__vm_order_item.mdate >= '.$db->Quote($ordermdate->toUnix());
		}
		
		// Filter by order modified date end
		$ordermdateend = $template->getValue('orderitemsmdateend', 'orderitem', false);
		if ($ordermdateend) {
			$ordermdate = JFactory::getDate($ordermdateend);
			$selectors[] = '#__vm_order_item.mdate <= '.$db->Quote($ordermdate->toUnix());
		}
		
		// Filter by order status
		$orderstatus = $template->getValue('orderitemstatus', 'orderitem', false);
		if ($orderstatus && $orderstatus[0] != '') {
			$selectors[] = '#__vm_order_item.order_status IN (\''.implode("','", $orderstatus).'\')';
		}
		
		// Filter by order price start
		$pricestart = $template->getValue('orderitemspricestart', 'orderitem', false, 'float');
		if ($pricestart) {                
			$selectors[] = '#__vm_orders.order_total >= '.$pricestart;
		}
		
		// Filter by order price end
		$priceend = $template->getValue('orderitemspriceend', 'orderitem', false, 'float');
		if ($priceend) {                
			$selectors[] = '#__vm_orders.order_total <= '.$priceend;
		}
		
		// Filter by order product
		$orderproduct = $template->getValue('orderitemproduct', 'orderitem', false);
		if ($orderproduct && $orderproduct[0] != '') {
			$selectors[] = '#__vm_order_item.order_item_sku IN (\''.implode("','", $orderproduct).'\')';
		}
		
		// Filter by order currency
		$ordercurrency = $template->getValue('orderitemcurrency', 'orderitem', false);
		if ($ordercurrency && $ordercurrency[0] != '') {
			$selectors[] = '#__vm_orders.order_currency IN (\''.implode("','", $ordercurrency).'\')';
		}
		
		// Check if we need to attach any selectors to the query
		if (count($selectors) > 0 ) $q .= ' WHERE '.implode(' AND ', $selectors)."\n";
		
		// Ignore fields
		$ignore = array('full_name');
		
		// Check if we need to group the orders together
		$groupby = $template->getValue('groupby', 'general', false, 'bool');
		if ($groupby) $q .= $this->getFilterBy('groupby', $ignore); 
		
		// Order by set field
		$q .= $this->getFilterBy('sort', $ignore);
		
		// 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) {
						$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 '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 'product_item_price':
							case 'product_final_price':
							case 'product_price':
								$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;
							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;
							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;
						}
					}
					
					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();
			}
		}
	}
}
?>