<?php
/**
 * User info 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: userinfoexport.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );
 
/**
 * Processor for user info exports
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Export
 */
class CsvivirtuemartModelUserInfoExport extends CsvivirtuemartModelExportfile {
	
	/**
	 * User info export
	 *
	 * Exports user info 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 'user_id':
					$userfields[] = $db->nameQuote('#__vm_user_info').'.'.$db->nameQuote('user_id');
					break;
				case 'shopper_group_id':
					$userfields[] = $db->nameQuote('#__vm_shopper_group').'.'.$db->nameQuote('shopper_group_id');
					break;
				case 'vendor_id':
					$userfields[] = $db->nameQuote('#__vm_shopper_vendor_xref').'.'.$db->nameQuote('vendor_id');
					break;
				case 'full_name':
					$userfields[] = $db->nameQuote('#__vm_user_info').'.'.$db->nameQuote('first_name');
					$userfields[] = $db->nameQuote('#__vm_user_info').'.'.$db->nameQuote('middle_name');
					$userfields[] = $db->nameQuote('#__vm_user_info').'.'.$db->nameQuote('last_name');
					break;
				case 'cdate':
					$userfields[] = $db->nameQuote('#__vm_user_info').'.'.$db->nameQuote('cdate');
					break;
				case 'mdate':
					$userfields[] = $db->nameQuote('#__vm_user_info').'.'.$db->nameQuote('mdate');
					break;
				case 'custom':
					break;
				default:
					$userfields[] = $db->nameQuote($field->field_name);
					break;
			}
		}
		
		// Execute the query
		$q = "SELECT ".implode(",", $userfields);
		$q .= " FROM #__vm_user_info
			LEFT JOIN #__vm_shopper_vendor_xref 
			ON #__vm_user_info.user_id = #__vm_shopper_vendor_xref.user_id
			LEFT JOIN #__vm_shopper_group
			ON #__vm_shopper_vendor_xref.shopper_group_id = #__vm_shopper_group.shopper_group_id
			LEFT JOIN #__vm_vendor
			ON #__vm_shopper_vendor_xref.vendor_id = #__vm_vendor.vendor_id
			LEFT JOIN #__users
			ON #__vm_user_info.user_id = #__users.id";
		
		// Check if there are any selectors
		$selectors = array();
		
		// Check if there are any selectors
		$selectors = array();
		// Filter by vendors
		$vendors = JRequest::getVar('vendors', false);
		$vendors = $template->getValue('vendors', 'userinfo', false);
		if ($vendors && $vendors[0] != '') {
			$selectors[] = '#__vm_shopper_vendor_xref.vendor_id IN (\''.implode("','", $vendors).'\')';
		}
		
		// Filter by permissions
		$permissions = $template->getValue('permissions', 'userinfo', false);
		if ($permissions && $permissions[0] != '') {
			$selectors[] = '#__vm_user_info.perms IN (\''.implode("','", $permissions).'\')';
		}
		
		// Filter by address type
		$address = $template->getValue('userinfo_address', 'userinfo', false);
		if ($address) {
			$selectors[] = '#__vm_user_info.address_type = '.$db->Quote(strtoupper($address));
		}
		
		// Filter by user info modified date start
		$date = $template->getValue('userinfomdatestart', 'userinfo', false);
		if ($date) {
			$userinfomdate = JFactory::getDate($date);
			$selectors[] = '#__vm_user_info.mdate >= '.$db->Quote($userinfomdate->toUnix());
		}
		
		// Filter by user info date end
		$date = $template->getValue('userinfomdateend', 'userinfo', false);
		if ($date) {
			$userinfomdate = JFactory::getDate($date);
			$selectors[] = '#__vm_user_info.mdate <= '.$db->Quote($userinfomdate->toUnix());
		}
		
		// Check if we need to attach any selectors to the query
		if (count($selectors) > 0 ) $q .= ' WHERE '.implode(' AND ', $selectors)."\n";
		
		// Array of fields not to handle
		$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':
								if (strlen(trim($fieldvalue)) == 0) $fieldvalue = $field->default_value;
								else $fieldvalue = date($template->getValue('export_date_format', 'general'), $fieldvalue);
								$this->addExportField($field->combine, $fieldvalue, $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);
								$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 'vendor_name':
								$fieldvalue = stripslashes($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 'shopper_group_discount':
								$shopper_group_discount =  number_format($record->shopper_group_discount, $template->getValue('export_price_format_decimal', 'general', 2, 'int'), $template->getValue('export_price_format_decsep', 'general'), $template->getValue('export_price_format_thousep', 'general'));
								if (strlen(trim($shopper_group_discount)) == 0) $shopper_group_discount = $field->default_value;
								$shopper_group_discount = CsviHelper::replaceValue($fieldreplace, $shopper_group_discount);
								$this->addExportField($field->combine, $shopper_group_discount, $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();
			}
		}
	}
}
?>