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

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

/**
 * Processor for product stock
 *
 * @package CSVIVirtueMart
 */
class CsvivirtuemartModelProductstockimport extends CsvivirtuemartModelImportfile {

	// Private tables
	/** @var object contains the vm_product table */
	private $_vm_product = null;

	// Private variables
	/** @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		Find out if I still need the record_identify
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getStart() {
		// Load the data
		$this->loadData();

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

		// Process data
		$this->product_sku = $this->validateInput('product_sku');
		$this->product_in_stock = $this->validateInput('product_in_stock');

		// Check for product_id
		if (!isset($this->product_id)) $this->product_id = $this->getProductId();

		if (!$this->product_id) {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_DEBUG_NO_SKU'));
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_NO_SKU_OR_ID'));
			return false;
		}
		else {
			// Set the record identifier
			$this->record_identity = (isset($this->product_sku)) ? $this->product_sku : $this->product_id;
			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() {
		$csvilog = JRequest::getVar('csvilog');
		$template = JRequest::getVar('template');

		if (!$template->getValue('overwrite_existing_data', 'general')) {
		   $csvilog->addDebug(JText::sprintf('COM_CSVIVIRTUEMART_DATA_EXISTS_PRODUCT_SKU', $this->product_sku));
		   $csvilog->AddStats('skipped', JText::sprintf('COM_CSVIVIRTUEMART_DATA_EXISTS_PRODUCT_SKU', $this->product_sku));
		}
		else {
			if (empty($this->product_sku) && empty($this->product_id)) {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_DEBUG_NO_SKU'));
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_NO_SKU_OR_ID'));
				return false;
			}
			else {
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_PROCESS_SKU').$this->record_identity);
			}

			if (!isset($this->product_id) && $template->getValue('ignore_non_exist', 'general')) {
				// Do nothing for new products when user chooses to ignore new products
				$csvilog->AddStats('skipped', JText::sprintf('COM_CSVIVIRTUEMART_DATA_EXISTS_IGNORE_NEW', $this->record_identity));
			}
			// User wants to add or update the product
			else {
				// Process product info
				if (!$this->_productQuery()) {
					$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_NO_UPDATE_PRODUCT_SKU', $this->product_sku));
				}
			}

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

	/**
	 * Creates either an update or insert SQL query for a product.
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access		private
	 * @param
	 * @return		bool true if the query executed successful | false if the query failed
	 * @since 		3.0
	 */
	private function _productQuery() {
		$csvilog = JRequest::getVar('csvilog');

		// Load the data first
		$this->_vm_product->load($this->product_id);

		// Split the modification
		$operation = substr($this->product_in_stock, 0, 1);
		$value = substr($this->product_in_stock, 1);

		// Get the database value
		$stock = $this->_vm_product->product_in_stock;

		// Check what modification we need to do and apply it
		switch ($operation) {
			case '+':
				$stock += $value;
				break;
			case '-':
				$stock -= $value;
				break;
			case '/':
				$stock /= $value;
				break;
			case '*':
				$stock*= $value;
				break;
			default:
				// Assign the current price to prevent it being overwritten
				$stock = $this->product_in_stock;
				break;
		}
		$this->_vm_product->product_in_stock = $stock;

		// Set some initial values
		// Set the modified date as we are modifying the product
		$this->_vm_product->mdate = time();

		// We have a succesful save, get the product_id
		if ($this->_vm_product->store()) {
			$csvilog->AddStats('updated', JText::_('COM_CSVIVIRTUEMART_UPDATE_PRODUCTSTOCK'));
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_PRODUCTSTOCK_QUERY'), true);
			return true;
		}
		else {
			$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_PRODUCTSTOCK_NOT_ADDED', $this->_vm_product->getError()));
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_PRODUCTSTOCK_QUERY'), true);
			return false;
		}
	}

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

	/**
	 * Cleaning the product stock related tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function cleanTables() {
		unset($this->_vm_product);
		unset($this->product_id);
		unset($this->product_sku);
		unset($this->product_in_stock);
	}
}
?>