<?php
/**
 * Product type names 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: producttypenamesexport.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * Processor for product type names exports
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Export
 */

class CsvivirtuemartModelProductTypenamesExport extends CsvivirtuemartModelExportfile {

	/**
	 * Product type names export
	 *
	 * Exports product type names 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');
		$producttypeid = $template->getValue('producttypenames', 'producttypename', false);

		// Build something fancy to only get the fieldnames the user wants
		$userfields = array();
		$vmtables = array();
		$vmids = array();

		foreach ($export_fields as $column_id => $field) {
			switch ($field->field_name) {
				case 'product_sku':
					$userfields[] = '#__vm_product.product_sku';
					break;
				case 'product_id':
					$userfields[] = '#__vm_product.product_id';
					break;
				case 'product_type_name':
					$userfields[] = '#__vm_product_type.product_type_name';
					break;
				case 'product_type_id':
					$userfields[] = '#__vm_product_type.product_type_id';
					break;
				// Man made fields, do not export them
				case 'custom':
					break;
				default:
					// Check which product type table belongs to the field
					$q = "SELECT vm_table FROM #__csvivirtuemart_available_fields WHERE csvi_name = ".$db->Quote($field->field_name)." AND vm_table LIKE 'vm_product_type_".$producttypeid."' LIMIT 1";
					$db->setQuery($q);
					$vmtables[$db->loadResult()][] = $field->field_name;
					$vmids[] = $db->loadResult();
					break;
			}
		}

		// Check if we have any product type tables to export
		$vmids = array_unique($vmids);

		if (!empty($vmids)) {
			/**
			 * Export SQL Query
			 * Get all products - including items as well as products without a price
			 */
			$queries = array();
			$filterid = '';
			$userfields = array_unique($userfields);
			foreach ($vmids AS $vmidkey => $vmid) {
				$q = "(SELECT ".implode(",\n", $userfields);
				foreach ($vmtables as $vmtableskey => $vmfields) {
					if ($vmid == $vmtableskey) {
						$filterid = str_replace('vm_product_type_', '', $vmid);
						foreach ($vmfields AS $vmfieldkey => $vmfield) {
							$q .= ",\n".$db->nameQuote('#__'.$vmid).'.'.$db->nameQuote($vmfield).' AS '.$vmfield;
						}
					}
					else {
						foreach ($vmfields AS $vmfieldkey => $vmfield) {
							$q .= ",\n '' AS ".$vmfield;
						}
					}
				}
				$q .= ' FROM #__vm_product_type
					LEFT JOIN #__vm_product_product_type_xref
					ON #__vm_product_product_type_xref.product_type_id = #__vm_product_type.product_type_id
					LEFT JOIN #__vm_product
					ON #__vm_product_product_type_xref.product_id = #__vm_product.product_id ';

				// Add the product type X tables
				$q .= "\nLEFT JOIN #__".$vmid." ON #__".$vmid.".product_id = #__vm_product.product_id "."\n";

				// Check if there are any selectors
				$selectors = array();

				// Add product type ID checks
				if (is_int($filterid)) $selectors[] = '#__vm_product_type.product_type_id = '.$filterid;

				// Filter by product type name
				if ($producttypeid) {
					$selectors[] = '#__vm_product_type.product_type_id = '.$producttypeid;
				}

				// Check if we need to attach any selectors to the query
				if (count($selectors) > 0 ) $q .= ' WHERE '.implode(' AND ', $selectors)."\n";

				// Special field treatment
				$special = array();
				$special['product_sku'] = $db->nameQuote('#__vm_product').'.'.$db->nameQuote('product_sku');
				$special['product_id'] = $db->nameQuote('#__vm_product').'.'.$db->nameQuote('product_id');
				$special['product_type_name'] = $db->nameQuote('#__vm_product_type').'.'.$db->nameQuote('product_type_name');
				$special['product_type_id'] = $db->nameQuote('#__vm_product_type').'.'.$db->nameQuote('product_type_id');

				// Check if we need to group the orders together
				$groupby = $template->getValue('groupby', 'general', false, 'bool');
				if ($groupby) $q .= $this->getFilterBy('groupby', array(), $special);

				// Order by set field
				$q .= $this->getFilterBy('sort', array(), $special);

				// Add export limits
				$q .= $this->getExportLimit();
				$queries[] = $q.')';
			}

			// Create the full query
			$q = implode("\nUNION\n", $queries);

			// 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) {
								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();
				}
			}
		}
		else {
			$this->addExportContent(JText::_('COM_CSVIVIRTUEMART_NO_DATA_FOUND'));
			$this->writeOutput();
			$csvilog->AddStats('incorrect', $db->getErrorMsg());
		}
	}
}
?>