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

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

/**
 * Processor for category details
 *
 * Main processor for importing categories.
 *
 * @package CSVIVirtueMart
 * @todo 	Check vendor ID
 */
class CsvivirtuemartModelCategorydetailsimport extends CsvivirtuemartModelImportfile {

	// Private tables
	/** @var object contains the vm_category table */
	private $_vm_category = null;

	// Public variables
	public $category_path = null;
	/** @var integer contains the category ID for a product */
	public $category_id = null;
	/** @var array contains the setting if the category needs to be deleted */
	public $category_delete = null;
	/** @var string contains the category full image */
	public $category_full_image = null;
	/** @var string contains the category thumb image */
	public $category_thumb_image = null;

	// Private variables
	/** @var bool set if settings are loaded or not */
	private $_settings_loaded = false;
	/** @var mixed contains the data of the current field being processed */
	private $_datafield = null;
	/** @var object contains general import functions */
	private $_importmodel = null;
	/** @var object contains general category functions */
	private $_categorymodel = null;
	/** @var string Category separator */
	private $_catsep = 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 general category functions
		$this->_categorymodel = $this->getModel('category');
		$this->_categorymodel->getStart();

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

		// Check for vendor ID
		$this->vendor_id = $this->getVendorId();

		// There is no category path, cannot continue
		if (!isset($this->_csvifields['category_path']) && !isset($this->_csvifields['category_id'])) {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_CATEGORY_PATH_SET'));
			return false;
		}
		// All good, let's continue
		else {
			// Get the uploaded values
			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 'category_products_per_row':
									$this->$name = $this->products_per_row = $this->_datafield;
									break;
								case 'category_list_order':
									$this->$name = $this->list_order = $this->_datafield;
									break;
								default:
									$this->$name = $this->_datafield;
									break;
							}
						}
					}
					else return false;
				}
			}
		}
		return true;
	}

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

	/**
	 * Cleaning the product related tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo 		Find out why the unset is there
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function cleanTables() {
		$this->_vm_category->reset();
		unset($this->category_name);

		// 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;
			}
		}
	}

	/**
	 * 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');

		// First get the category ID
		if (!isset($this->category_id)) {
			$categoryid = $this->_categorymodel->getCategoryIdFromPath($this->category_path);
			// If we can't get a category ID we cannot continue
			if (!$categoryid) {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_COULD_NOT_FIND_A_CATEGORY_ID'));
				return false;
			}
			else $this->category_id = $categoryid['category_id'];
		}

		// We have the category ID, lets see if it should be deleted
		if ($this->category_delete == 'Y') {
			// Bind the data
			$this->_vm_category->bind($this);
			if ($this->_vm_category->delete()) {
				$csvilog->AddStats('deleted', JText::_('COM_CSVIVIRTUEMART_CATEGORY_DELETED'));
			}
			else {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_CATEGORY_NOT_DELETED'));
			}
		}
		else {
			// Check if any image handling needs to be done
			if (!is_null($this->category_full_image)) {
				if (is_null($this->category_thumb_image)) $this->category_thumb_image = basename($this->category_full_image);
				// Image handling
				$imagehelper = new ImageHelper;
				// Process the file details
				$file_details = $imagehelper->ProcessImage($this->category_full_image, $this->category_thumb_image, $template->getValue('file_location_category_images', 'path'));
				if ($file_details['full_image']['exists'] && $file_details['full_image']['isimage']) {
					$this->category_full_image = (empty($file_details['full_image']['output_folder'])) ? $file_details['full_image']['output_name'] : $file_details['full_image']['output_folder'].'/'.$file_details['full_image']['output_name'];
					$this->category_thumb_image = $file_details['thumb_image']['output_folder'].'/'.$file_details['thumb_image']['output_name'];
				}
				// See if we need to empty the image data
				else if ($template->getValue('empty_image', 'image')) {
					$this->category_full_image = '';
					$this->category_thumb_image = '';
				}
			}
			else {
				$csvilog->AddStats('skipped', JText::_('COM_CSVIVIRTUEMART_NO_THUMB_FULL_IMAGE_IN_FILE'));
			}

			// Set some basic values
			if (!isset($this->mdate)) $this->mdate = time();

			// Check if the category_name matches the last entry in the category_path
			if (isset($this->category_name)){
				// Load the category separator
				if (is_null($this->_catsep)) {
					$template = JRequest::getVar('template');
					$this->_catsep = $template->getValue('category_separator', 'general', '/');
				}

				$catparts = explode($this->_catsep, $this->category_path);
				end($catparts);
				if (current($catparts) != $this->category_name) {
					$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_CATEGORY_NAME_NO_MATCH_CATEGORY_PATH'));
					return false;
				}
			}

			// All fields have been processed, bind the data
			$this->_vm_category->bind($this);

			// Now store the data
			if ($this->_vm_category->store()) {
				if ($this->queryResult() == 'UPDATE') $csvilog->AddStats('updated', JText::_('COM_CSVIVIRTUEMART_UPDATE_CATEGORY_DETAILS'));
				else $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ADD_CATEGORY_DETAILS'));
			}
			else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_CATEGORY_DETAILS_NOT_ADDED', $this->_vm_category->getError()));

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

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