<?php
/**
 * Order item import
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Import
 * @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: orderitemimport.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 import
 *
 * @package CSVIVirtueMart
 */
class CsvivirtuemartModelOrderitemimport extends CsvivirtuemartModelImportfile {

	// Private tables
	/** @var object contains the vm_orders table */
	private $_vm_order_item = null;

	// Public variables
	/** @var int contains the order ID */
	public $order_id = null;
	/** @var int contains the unique orders item database ID */
	public $order_item_id = null;
	/** @var int unique user info ID */
	public $user_info_id = null;
	/** @var string contains the product SKU */
	public $product_sku = null;
	/** @var int contains the product ID */
	public $product_id = null;
	/** @var int contains the product SKU for the order */
	public $order_item_sku = null;
	/** @var int contains the user email */
	public $user_email = null;
	/** @var int contains the user email */
	public $user_id = null;

	// Private variables
	/** @var mixed contains the data of the current field being processed */
	private $_datafield = null;
	/** @var object contains general import functions */
	private $_importmodel = null;

	/**
	 * Constructor
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.4
	 */
	public function __construct() {
		parent::__construct();
		// Load the tables that will contain the data
		$this->_loadTables();
		$this->loadSettings();
    }

    /**
     * Refresh the settings for XML nodes
     *
     * @copyright
     * @author 		RolandD
     * @todo
     * @see
     * @access 		protected
     * @param
     * @return
     * @since 		3.8.2
     */
	protected function refresh() {
		$this->loadSettings();
	}

	/**
	 * Here starts the processing
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getStart() {
		// Load the data
		$this->loadData();

		// Get the logger
		$csvilog = JRequest::getVar('csvilog');

		// Load some basic info
		$this->vendor_id = $this->getVendorId();

		// Process data
		foreach ($this->_csvifields as $name => $details) {
			if ($details['published']) {
				$this->_datafield = $this->validateInput($name);
				if ($this->_datafield !== false) {
					// Check if we are dealing with the last field
					if ($details == $this->_lastfield) $details['combine'] = false;

					// See if we are combining the field
					if ($details['combine']) $this->setCombineField($this->_datafield, $name);
					else {
						// Check if there are any fields to be combined
						if (!empty($this->combine_fields)) {
							// Get the fieldname the combine is for
							$name = $this->combine_settings['fieldname'];
							// Add the current data
							$this->setCombineField($this->_datafield);
							// Get the combined data
							$this->_datafield = $this->getCombineField();
						}
						// Check if the field needs extra treatment
						switch ($name) {
							case 'product_price':
								$this->product_item_price = $this->cleanPrice($this->_datafield);
								break;
							case 'product_final_price':
								$this->$name = $this->cleanPrice($this->_datafield);
								 break;
							case 'product_sku':
								$this->order_item_sku = $this->_datafield;
								$this->product_sku = $this->_datafield;
								break;
							case 'product_name':
								$this->order_item_name = $this->_datafield;
								break;
							case 'cdate':
								$this->cdate = $this->convertDate($this->_datafield);
								break;
							case 'mdate':
								$this->mdate = $this->convertDate($this->_datafield);
								break;
							case 'address_type':
								switch (strtolower($this->_datafield)) {
									case 'shipping address':
									case 'st':
										$this->$name = 'ST';
										break;
									case 'billing address':
									case 'bt':
									default:
										$this->$name = 'BT';
										break;
								}
								break;
							default:
								$this->$name = $this->_datafield;
								break;
						}
					}
				}
				else return false;
			}
		}
		return true;
	}

	/**
	 * Process each record and store it in the database
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getProcessRecord() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');

		// Check if we have a user_info_id
		if (!isset($this->user_info_id)) {
			if (!$this->user_id && $this->user_email) {
				$q = "SELECT id FROM #__users WHERE email = ".$db->Quote($this->user_email);
				$db->setQuery($q);
				$this->user_id = $db->loadResult();
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_RETRIEVE_USER_ID'), true);
			}
			// Retrieve the user info ID if possible
			if ($this->user_id && $this->address_type && $this->address_type_name) {
				$q = "SELECT user_info_id
					FROM #__vm_user_info
					WHERE user_id = ".$this->user_id."
					AND address_type = ".$db->Quote($this->address_type)."
					AND address_type_name = ".$db->Quote($this->address_type_name);
				$db->setQuery($q);
				$this->user_info_id = $db->loadResult();
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_CHECK_USER_INFO_ID'), true);
			}
			else {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_ADDRESS_TYPE_OR_ADDRESS_TYPE_NAME'));
				return false;
			}
			if (empty($this->user_info_id)) {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_USER_INFO_ID_FOUND'));
				return false;
			}
		}

		// Check for product ID
		if (!isset($this->product_id) && isset($this->product_sku)) {
			$q = "SELECT product_id
				FROM #__vm_product
				WHERE product_sku = ".$db->Quote($this->product_sku);
			$db->setQuery($q);
			$this->product_id = $db->loadResult();
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_CHECK_PRODUCT_ID'), true);

			if (empty($this->product_id)) {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_PRODUCT_ID_FOUND'));
				return false;
			}
		}
		else if (isset($this->product_id) && !isset($this->product_sku)) {
			$q = "SELECT product_sku
				FROM #__vm_product
				WHERE product_id = ".$this->product_id;
			$db->setQuery($q);
			$this->order_item_sku = $db->loadResult();
		}
		else if (!isset($this->product_id) && !isset($this->product_sku)) {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_PRODUCT_ID_OR_SKU'));
			return false;
		}

		// Check if there is an existing order item
		$q = "SELECT order_item_id
			FROM #__vm_order_item
			WHERE order_id = ".$this->order_id."
			AND user_info_id = ".$db->Quote($this->user_info_id)."
			AND product_id = ".$this->product_id;
		$db->setQuery($q);
		$this->order_item_id = $db->loadResult();

		// Bind the data
		$this->_vm_order_item->bind($this);

		// Check if we have a product name
		if (empty($this->_vm_order_item->order_item_name)) {
			$q = "SELECT product_name
				FROM #__vm_product
				WHERE product_id = ".$this->product_id;
			$db->setQuery($q);
			$this->_vm_order_item->order_item_name = $db->loadResult();
		}

		// Check if there is a cdate
		if (empty($this->_vm_order_item->cdate)) $this->_vm_order_item->cdate = time();

		// Check if there is a cdate
		if (empty($this->_vm_order_item->cdate)) $this->_vm_order_item->mdate = time();

		// Check for an existing order item
		$this->_vm_order_item->check();

		// Store the data
		if ($this->_vm_order_item->store()) {
			if ($this->queryResult() == 'UPDATE') $csvilog->AddStats('updated', JText::_('COM_CSVIVIRTUEMART_UPDATE_ORDER_ITEM'));
			else $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ADD_ORDER_ITEM'));
		}
		else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_ORDER_ITEM_NOT_ADDED', $this->_vm_order_item->getError()));

		// Store the debug message
		$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_ORDER_ITEM_QUERY'), true);

		// Clean the tables
		$this->cleanTables();
	}

	/**
	 * Load the order item related tables
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.0
	 */
	private function _loadTables() {
		$this->_vm_order_item = $this->getTable('vm_order_item');
	}

	/**
	 * Cleaning the order item related tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function cleanTables() {
		$this->_vm_order_item->reset();

		// Clean local variables
		$class_vars = get_class_vars(get_class($this));
		foreach ($class_vars as $name => $value) {
			if (substr($name, 0, 1) != '_') {
				$this->$name = $value;
			}
		}
	}
}
?>
