<?php
/**
 * Install model
 *
 * @package 	CSVIVirtueMart
 * @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: install.php 1892 2012-02-11 11:01:09Z RolandD $
 */

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

jimport( 'joomla.application.component.model' );

/**
 * Install Model
 *
 * @package CSVIVirtueMart
 */
class CsvivirtuemartModelInstall extends JModel {

	/** */
	private $_templates = array();
	private $_tag = '';
	private $_results = array();

	/**
	 * Find the version installed
	 *
	 * 1.5+ = 1.5/1.6
	 * 1.7+ = 1.7/1.8/1.9
	 * 2.0  = 2.0
	 * 2.1+ = 2.1/2.2/2.3
	 * 3.0+ = 3.0/3.1
	 * 3.2 = 3.2
	 * 3.2.1 = 3.2.1
	 * 3.2.2 = 3.2.2
	 * 3.2.3 = 3.2.3
	 * 3.3 = 3.3
	 * 3.3.1 = 3.3.1
	 * 3.4 = 3.4
	 * 3.5 = 3.5
	 * 3.6 = 3.6
	 * 3.7 = 3.7
	 * 3.8 = 3.8
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo 		Check version from database
	 * @see
	 * @access 		private
	 * @param
	 * @return 		string	the version determined by the database
	 * @since 		3.0
	 */
	public function getVersion() {
		// Determine the tables in the database
		$version = '';
		// See if the version is 3.0+
		if ($this->_tableExists('#__csvivirtuemart_template_settings')) {
			$dbversion = $this->_getVersion();
			if (strpos($dbversion, '.') === false) $version = '3.0+';
			else $version = $dbversion;
		}
		else {
			// Check first if a version 2.x is installed
			$csvivirtuemart_table = $this->_tableExists('#__csvivirtuemart_templates');
			if ($csvivirtuemart_table) {
				// See if the version is 2.0 or 2.1+
				if ($this->_tableExists('#__csvivirtuemart_settings')) {
					$version = '2.1+';
				}
				else $version = '2.0';
			}
			else {
				$csvi_table = $this->_tableExists('#__csvi_templates');
				if ($csvi_table) {
					// See if the version is 1.5/1.6 or 1.7/1.8/1.9
					if ($this->_tableExists('#__csvi_currency')) {
						$version = '1.7+';
					}
					else $version = '1.5+';
				}
				else $version = 'current';
			}
		}

		return $version;
	}

	/**
	 * Start performing the upgrade
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return 		string	the result of the upgrade
	 * @since 		3.0
	 */
	public function getUpgrade() {
		// Get the currently installed version
		$version = $this->_translateVersion();

		// Rename the existing tables
		if ($this->_renameTables($version)) {
			// Create the new tables
			if ($this->_createTables()) {
				if ($version == 'current') {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_INSTALL_OK');
				}
				else {
					// Migrate the data in the tables
					if ($this->_migrateTables($version)) $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_UPGRADE_OK');

					// Move the temporary files
					if ($this->_movetmp()) $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_MOVE_TMP_OK');

					// Update the version number in the database
					$this->_setVersion();
				}
			}
			else $this->_results['error'][] = '<span class="error">'.JText::_('COM_CSVIVIRTUEMART_INSTALL_NOK').'</span>';
		}
		else {
			$this->_results['error'][] = '<span class="error">'.JText::_('COM_CSVIVIRTUEMART_INSTALL_NOK').'</span>';
			JRequest::setVar('cancelinstall', true);
		}

		// Send the results back
		return $this->_results;
	}

	/**
	 * Rename the existing tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param 		string	$version	the currently installed version
	 * @return 		bool	true if tables are renamed | false if tables are not renamed
	 * @since 		3.0
	 */
	private function _renameTables($version) {
		$db = JFactory::getDBO();
		$this->_tag = str_ireplace('.', '_', $version);
		$ok = true;
		$removeold = JRequest::getBool('removeoldtables');
		$random = time();

		// Load the tables to rename
		$tables = $this->_getTables($version);

		// Start renaming the tables
		foreach ($tables as $table) {
			if ($this->_tableExists($table)) {
				if ($this->_tableExists($table.'_'.$this->_tag)) {
					if ($removeold) {
						$db->setQuery("DROP TABLE ".$db->nameQuote($table.'_'.$this->_tag));
						if (!$db->query()) {
							$this->_results['messages'][] = $db->getErrorMsg();
							$ok = false;
						}
					}
					else {
						$db->setQuery("ALTER TABLE ".$db->nameQuote($table.'_'.$this->_tag)." RENAME TO ".$db->nameQuote($table.'_'.$random));
						if (!$db->query()) {
							$this->_results['messages'][] = $db->getErrorMsg();
							$ok = false;
						}
					}
				}
				$db->setQuery("ALTER TABLE ".$db->nameQuote($table)." RENAME TO ".$db->nameQuote($table.'_'.$this->_tag));
				if (!$db->query()) {
					$this->_results['messages'][] = $db->getErrorMsg();
					$ok = false;
				}
			}
			$_results['messages'][] = $table;
		}
		return $ok;
	}

	/**
	 * Check if a table exists
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		$table	string	the name of the table to check
	 * @return 		bool	true if table exists | false if table does not exist
	 * @since 		3.0
	 */
	private function _tableExists($table) {
		$db = JFactory::getDBO();
		$conf = JFactory::getConfig();
		$table = str_ireplace('#__', $conf->getValue('config.dbprefix'), $table);
		$q = "SELECT table_name FROM information_schema.tables WHERE table_schema = ".$db->Quote($conf->getValue('config.db'))." AND table_name = ".$db->Quote($table);
		$db->setQuery($q);
		$total = $db->loadResult();
		if (!empty($total)) return true;
		else return false;
	}

	/**
	 * Create the tables for this version
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo 		Remove return statement
	 * @see
	 * @access 		private
	 * @param
	 * @return 		bool	true on creating all tables | false if table is not created
	 * @since 		3.0
	 */
	private function _createTables() {
		$this->_createTemplateSettings();
		$this->_createTemplateTypes();
		$this->_createLogs();
		$this->_createLogDetails();
		$this->_createAvailableFields();
		$this->_createCurrency();
		$this->_createSettings();
		$this->_createIcecatIndex();
		$this->_createIcecatSuppliers();
		$this->_createRelatedProducts();

		return true;
	}

	/**
	 * Migrate the tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		string	$version	the version being migrated from
	 * @return 		bool	true if migration is OK | false if errors occured during migration
	 * @since 		3.0
	 */
	private function _migrateTables($version) {
		$db = JFactory::getDBO();

		switch ($version) {
			case '1.5':
				// Templates
				$db->setQuery('SELECT * FROM '.$db->nameQuote('#__csvi_templates_'.$this->_tag));
				$templates = $db->loadObjectList();
				if ($templates) {
					$this->_convertTemplate($templates, $version);
					// Store the templates
					$this->_storeTemplates($version);
				}
				else $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_NO_TEMPLATES_CONVERT');
				// Logs
				$this->_convertLog($version);
				// Currencies do not exist
				// Settings do not exist
				break;
			case '1.7':
				// Templates
				$db->setQuery('SELECT * FROM '.$db->nameQuote('#__csvi_templates_'.$this->_tag));
				$templates = $db->loadObjectList();
				if ($templates) {
					$this->_convertTemplate($templates, $version);
					// Store the templates
					$this->_storeTemplates($version);
				}
				else $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_NO_TEMPLATES_CONVERT');

				// Logs
				$this->_convertLog($version);

				// Currency
				$this->_convertCurrency($version);

				// Settings do not exist
				break;
			case '2.0':
				// Templates
				$db->setQuery('SELECT * FROM '.$db->nameQuote('#__csvivirtuemart_templates_'.$this->_tag));
				$templates = $db->loadObjectList();
				if ($templates) {
					$this->_convertTemplate($templates, $version);
					// Store the templates
					$this->_storeTemplates($version);
				}
				else $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_NO_TEMPLATES_CONVERT');

				// Logs
				$this->_convertLog($version);

				// Currency
				$this->_convertCurrency($version);

				// Settings do not exist
				break;
			case '2.1':
				// Templates
				$db->setQuery('SELECT * FROM '.$db->nameQuote('#__csvivirtuemart_templates_'.$this->_tag));
				$templates = $db->loadObjectList();
				if ($templates) {
					$this->_convertTemplate($templates, $version);
					// Store the templates
					$this->_storeTemplates($version);
				}
				else $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_NO_TEMPLATES_CONVERT');

				// Logs
				$this->_convertLog($version);

				// Currency
				$this->_convertCurrency($version);

				// Settings
				$this->_convertSetting($version);
				break;
			case '3.0':
				// Templates
				$db->setQuery('SELECT * FROM '.$db->nameQuote('#__csvivirtuemart_template_settings_'.$this->_tag));
				$templates = $db->loadObjectList();
				if (count($templates) > 0) {
					// Store the templates
					$this->_storeTemplates($version);
				}
				else $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_NO_TEMPLATES_CONVERT');

				// Logs
				$this->_convertLog($version);

				// Currency
				$this->_convertCurrency($version);

				// Settings
				$this->_convertSetting($version);
				break;
		}
	}

	/**
	 * Get the tables per version
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		string	$version	the current installed version
	 * @return 		array	list of tables
	 * @since 		3.0
	 */
	private function _getTables($version) {
		$tables = array();
		switch ($version) {
			case '1.5':
				$tables[] = '#__csvi_available_fields';
				$tables[] = '#__csvi_logs';
				$tables[] = '#__csvi_log_details';
				$tables[] = '#__csvi_templates';
				$tables[] = '#__csvi_template_fields';
				$tables[] = '#__csvi_template_types';
				break;
			case '1.7':
				$tables[] = '#__csvi_available_fields';
				$tables[] = '#__csvi_currency';
				$tables[] = '#__csvi_logs';
				$tables[] = '#__csvi_log_details';
				$tables[] = '#__csvi_templates';
				$tables[] = '#__csvi_template_fields';
				$tables[] = '#__csvi_template_types';
				break;
			case '2.0':
			case '2.1':
				$tables[] = '#__csvivirtuemart_available_fields';
				$tables[] = '#__csvivirtuemart_currency';
				$tables[] = '#__csvivirtuemart_logs';
				$tables[] = '#__csvivirtuemart_log_details';
				$tables[] = '#__csvivirtuemart_replacements';
				$tables[] = '#__csvivirtuemart_settings';
				$tables[] = '#__csvivirtuemart_templates';
				$tables[] = '#__csvivirtuemart_template_fields';
				$tables[] = '#__csvivirtuemart_template_types';
				break;
			case '3.0':
			case 'current':
			default:
				$tables[] = '#__csvivirtuemart_available_fields';
				$tables[] = '#__csvivirtuemart_currency';
				$tables[] = '#__csvivirtuemart_icecat_index';
				$tables[] = '#__csvivirtuemart_icecat_suppliers';
				$tables[] = '#__csvivirtuemart_logs';
				$tables[] = '#__csvivirtuemart_log_details';
				$tables[] = '#__csvivirtuemart_settings';
				$tables[] = '#__csvivirtuemart_template_settings';
				$tables[] = '#__csvivirtuemart_template_types';
				$tables[] = '#__csvivirtuemart_related_products';
				break;
		}
		return $tables;
	}

	/**
	 * Create the template settings table
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return 		bool	true if query is succesful | false if query fails
	 * @since 		3.0
	 */
	private function _createTemplateSettings() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_template_settings` (
				`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique ID for the saved setting',
				`name` VARCHAR(255) NOT NULL COMMENT 'Name for the saved setting',
				`settings` TEXT NOT NULL COMMENT 'The actual settings',
				`type` ENUM('import','export') NOT NULL COMMENT 'The type of settings',
				PRIMARY KEY (`id`),
				UNIQUE INDEX `Unique name` (`type`, `name`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Stores the import and export saved settings for CSVI VirtueMart';");
		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createTemplateTypes() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS  `#__csvivirtuemart_template_types` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `template_type_name` varchar(55) NOT NULL,
			  `template_type` varchar(55) NOT NULL,
			  `component` VARCHAR(55) NOT NULL COMMENT 'Name of the component',
			  PRIMARY KEY  (`id`),
			  UNIQUE KEY `type_name` (`template_type_name`,`template_type`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Template types for CSVI VirtueMart';");
		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
		else {
			$columns = $db->getTableFields('#__csvivirtuemart_template_types');
			if (!array_key_exists('component', $columns['#__csvivirtuemart_template_types'])) {
				$db->setQuery("ALTER TABLE `#__csvivirtuemart_template_types`
					ADD COLUMN `component` VARCHAR(55) NOT NULL COMMENT 'Name of the component' AFTER `template_type`");
				if (!$db->query()) {
					$this->_results['messages'][] = $db->getErrorMsg();
					return false;
				}
			}

			$db->setQuery("INSERT IGNORE INTO `#__csvivirtuemart_template_types` (`template_type_name`, `template_type`, `component`) VALUES
			('categorydetailsexport', 'export', 'com_virtuemart'),
			('categorydetailsimport', 'import', 'com_virtuemart'),
			('couponsexport', 'export', 'com_virtuemart'),
			('couponsimport', 'import', 'com_virtuemart'),
			('customexport', 'export', 'com_virtuemart'),
			('customimport', 'import', 'com_virtuemart'),
			('manufacturercategoryimport', 'import', 'com_virtuemart'),
			('manufacturerexport', 'export', 'com_virtuemart'),
			('manufacturerimport', 'import', 'com_virtuemart'),
			('multiplepricesexport', 'export', 'com_virtuemart'),
			('multiplepricesimport', 'import', 'com_virtuemart'),
			('orderexport', 'export', 'com_virtuemart'),
			('orderimport', 'import', 'com_virtuemart'),
			('orderitemexport', 'export', 'com_virtuemart'),
			('orderitemimport', 'import', 'com_virtuemart'),
			('productexport', 'export', 'com_virtuemart'),
			('productfilesexport', 'export', 'com_virtuemart'),
			('productfilesimport', 'import', 'com_virtuemart'),
			('productimport', 'import', 'com_virtuemart'),
			('productreviewsexport', 'export', 'com_virtuemart'),
			('productreviewsimport', 'import', 'com_virtuemart'),
			('productstockimport', 'import', 'com_virtuemart'),
			('producttypeexport', 'export', 'com_virtuemart'),
			('producttypeimport', 'import', 'com_virtuemart'),
			('producttypenamesexport', 'export', 'com_virtuemart'),
			('producttypenamesimport', 'import', 'com_virtuemart'),
			('producttypeparametersexport', 'export', 'com_virtuemart'),
			('producttypeparametersimport', 'import', 'com_virtuemart'),
			('shippingratesexport', 'export', 'com_virtuemart'),
			('shippingratesimport', 'import', 'com_virtuemart'),
			('taxratesexport', 'export', 'com_virtuemart'),
			('taxratesimport', 'import', 'com_virtuemart'),
			('userfieldsexport', 'export', 'com_virtuemart'),
			('userfieldsimport', 'import', 'com_virtuemart'),
			('waitinglistexport', 'export', 'com_virtuemart'),
			('waitinglistimport', 'import', 'com_virtuemart'),
			('userinfoexport', 'export', 'com_virtuemart'),
			('userinfoimport', 'import', 'com_virtuemart'),
			('vmf_featuresexport', 'export', 'com_vmfiltering'),
			('vmf_valuesexport', 'export', 'com_vmfiltering'),
			('vmf_featuresimport', 'import', 'com_vmfiltering'),
			('vmf_valuesimport', 'import', 'com_vmfiltering');");

			if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
		}
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	public function _createLogs() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_logs` (
			  `id` int(11) NOT NULL auto_increment,
			  `userid` int(11) NOT NULL,
			  `logstamp` datetime NOT NULL,
			  `action` varchar(255) NOT NULL,
			  `action_type` varchar(255) NOT NULL default '',
			  `template_name` varchar(255) NULL default NULL,
			  `records` int(11) NOT NULL,
			  `run_id` INT(11) NULL DEFAULT NULL,
			  `file_name` VARCHAR(255) NULL DEFAULT NULL,
			  `run_cancelled` TINYINT(1) NOT NULL DEFAULT '0',
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Logging results for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createLogDetails() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_log_details` (
			  `id` int(11) NOT NULL auto_increment,
			  `log_id` int(11) NOT NULL,
			  `line` INT(11) NOT NULL,
			  `description` TEXT NOT NULL,
			  `result` varchar(45) NOT NULL,
			  `status` varchar(45) NOT NULL,
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Log details for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createAvailableFields() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_available_fields` (
			  `id` int(11) NOT NULL auto_increment,
			  `csvi_name` varchar(255) NOT NULL,
			  `vm_name` varchar(55) NOT NULL,
			  `vm_table` varchar(55) NOT NULL,
			  `core` TINYINT(1) NOT NULL DEFAULT '0',
			  `isprimary` TINYINT(1) NOT NULL DEFAULT '0',
			  PRIMARY KEY  (`id`),
			  UNIQUE INDEX `vm_name_table` (`vm_name`, `vm_table`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Available fields for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createCurrency() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS  `#__csvivirtuemart_currency` (
			  `currency_id` tinyint(4) NOT NULL auto_increment,
			  `currency_code` varchar(3) NULL DEFAULT NULL,
			  `currency_rate` varchar(55) NULL DEFAULT NULL,
			  PRIMARY KEY  (`currency_id`),
			  UNIQUE INDEX `currency_code` (`currency_code`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Curriencies and exchange rates for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createSettings() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_settings` (
				`id` INT(11) NOT NULL auto_increment,
				`params` TEXT NOT NULL,
				PRIMARY KEY (`id`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Configuration values for CSVI VirtueMart';");
		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
		else {
			$db->setQuery("INSERT IGNORE INTO `#__csvivirtuemart_settings` (`id`, `params`) VALUES (1, 'hostname=
				log_store=1
				import_nolines=0
				import_preview=5
				import_wait=5
				gb_title=
				gb_link=
				gb_description=');");

			if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
		}

	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createIcecatIndex() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_icecat_index` (
			  `path` varchar(100) DEFAULT NULL,
			  `product_id` int(2) DEFAULT NULL,
			  `updated` int(14) DEFAULT NULL,
			  `quality` varchar(6) DEFAULT NULL,
			  `supplier_id` int(1) DEFAULT NULL,
			  `prod_id` varchar(16) DEFAULT NULL,
			  `catid` int(3) DEFAULT NULL,
			  `m_prod_id` varchar(10) DEFAULT NULL,
			  `ean_upc` varchar(10) DEFAULT NULL,
			  `on_market` int(1) DEFAULT NULL,
			  `country_market` varchar(10) DEFAULT NULL,
			  `model_name` varchar(26) DEFAULT NULL,
			  `product_view` int(5) DEFAULT NULL,
			  `high_pic` varchar(51) DEFAULT NULL,
			  `high_pic_size` int(5) DEFAULT NULL,
			  `high_pic_width` int(3) DEFAULT NULL,
			  `high_pic_height` int(3) DEFAULT NULL,
			  INDEX `product_mpn` (`prod_id`),
			  INDEX `manufacturer_name` (`supplier_id`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='ICEcat index data for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Method Description
	 *
	 * @copyright
	 * @author
	 * @todo
	 * @see
	 * @access
	 * @param
	 * @return
	 * @since
	 */
	private function _createIcecatSuppliers() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_icecat_suppliers` (
				`supplier_id` INT(11) UNSIGNED NOT NULL,
				`supplier_name` VARCHAR(255) NOT NULL,
				UNIQUE INDEX `Unique supplier` (`supplier_id`, `supplier_name`),
				INDEX `Supplier name` (`supplier_name`)
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='ICEcat supplier data for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Create the related products table
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.3.1
	 */
	private function _createRelatedProducts() {
		$db = JFactory::getDBO();
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__csvivirtuemart_related_products` (
				`product_sku` VARCHAR(64) NOT NULL,
				`related_sku` TEXT NOT NULL
			) ENGINE=MyISAM CHARSET=utf8 COMMENT='Related products import for CSVI VirtueMart';");

		if (!$db->query()) $this->_results['messages'][] = $db->getErrorMsg();
	}

	/**
	 * Convert old templates to new templates
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param 		object	$templates	list of templates to be converted
	 * @param		string	$version	the version to convert from
	 * @return
	 * @since 		3.0
	 */
	private function _convertTemplate($templates, $version) {
		$db = JFactory::getDBO();

		// Go through the templates
		foreach ($templates as $key => $template) {
			// Get the template fields
			switch ($version) {
				case '1.5':
				case '1.7':
					// Load the fields
					$db->setQuery('SELECT * FROM #__csvi_template_fields'.'_'.$this->_tag.' WHERE field_template_id = '.$template->template_id);
					$template->fields = $db->loadObjectList();
					// Replacements did not exist
					$template->replacement = false;
					break;
				case '2.0':
					// Load the fields
					$db->setQuery('SELECT * FROM #__csvivirtuemart_template_fields'.'_'.$this->_tag.' WHERE field_template_id = '.$template->template_id);
					$template->fields = $db->loadObjectList();
					// Load the replacements
					$db->setQuery('SELECT *, "" AS selected_name FROM #__csvivirtuemart_replacements'.'_'.$this->_tag.' WHERE template_id = '.$template->template_id);
					$template->replacement = $db->loadObjectList();
					break;
				case '2.1':
					// Load the fields
					$db->setQuery('SELECT * FROM #__csvivirtuemart_template_fields'.'_'.$this->_tag.' WHERE field_template_id = '.$template->template_id);
					$template->fields = $db->loadObjectList();
					// Load the replacements
					$db->setQuery("SELECT COUNT(*) AS total FROM #__csvivirtuemart_template_types WHERE template_type_name = 'orderimport'");
					$found = $db->loadResult();
					if (!$found) {
						// Version is 2.1
						$db->setQuery('SELECT *, "" AS selected_name FROM #__csvivirtuemart_replacements'.'_'.$this->_tag.' WHERE template_id = '.$template->template_id);
					}
					else {
						// Version is 2.2+
						$db->setQuery('SELECT r.*, CONCAT(f.field_name, f.field_column_header) AS selected_name
									FROM #__csvivirtuemart_replacements'.'_'.$this->_tag.' AS r
									LEFT JOIN #__csvivirtuemart_template_fields'.'_'.$this->_tag.' AS f
									ON r.field_id = f.id
									WHERE r.template_id = '.$template->template_id);
					}
					$template->replacement = $db->loadObjectList();
					break;
			}

			// Check the template type
			if (strpos($template->template_type, 'import')) $this->_templates[] = $this->_importTemplate($template);
			else if (strpos($template->template_type, 'export')) $this->_templates[] = $this->_exportTemplate($template);
		}
	}

	/**
	 * Convert an import template
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return 		array	containing the converted template
	 * @since 		3.0
	 */
	private function _importTemplate($template) {

		$ctemplate = array();
		// Template settings
		$ctemplate['id'] = $template->template_id;
		$ctemplate['name'] = $template->template_name;

		// General settings
		$ctemplate['import_type'] = $template->template_type;
		$ctemplate['general']['loadfrom'] = 'fromupload';
		$ctemplate['general']['local_csv_file'] = '';
		$ctemplate['general']['urlfile'] = '';
		$ctemplate['general']['ftphost'] = '';
		$ctemplate['general']['ftpport'] = '';
		$ctemplate['general']['ftpusername'] = '';
		$ctemplate['general']['ftppass'] = '';
		$ctemplate['general']['ftproot'] = '';
		$ctemplate['general']['ftpfile'] = '';
		if (isset($template->auto_detect_delimiters)) $ctemplate['general']['auto_detect_delimiters'] = $template->auto_detect_delimiters;
		else $ctemplate['general']['auto_detect_delimiters'] = 1;
		$ctemplate['general']['category_separator'] = '/';
		$ctemplate['general']['use_column_headers'] = $template->use_column_headers;
		$ctemplate['general']['skip_first_line'] = $template->skip_first_line;
		$ctemplate['general']['overwrite_existing_data'] = $template->overwrite_existing_data;
		$ctemplate['general']['ignore_non_exist'] = $template->ignore_non_exist;
		$ctemplate['general']['skip_default_value'] = $template->skip_default_value;
		$ctemplate['general']['show_preview'] = $template->show_preview;
		$ctemplate['general']['collect_debug_info'] = $template->collect_debug_info;
		$ctemplate['general']['refresh_xml_headers'] = 0;
		if (isset($template->xml_nodes_map)) $ctemplate['general']['xml_nodes_map'] = $template->xml_nodes_map;
		else $ctemplate['general']['xml_nodes_map'] = '<item />';

		// Product settings
		$ctemplate['product']['update_based_on'] = 'product_sku';
		$ctemplate['product']['mpn_column_name'] = '';
		if (isset($template->unpublish_before_import)) $ctemplate['product']['unpublish_before_import'] = $template->unpublish_before_import;
		else $ctemplate['product']['unpublish_before_import'] = 0;
		$ctemplate['product']['use_icecat'] = 0;

		// Category settings
		$ctemplate['category']['append_categories'] = $template->append_categories;

		// Image settings
		$ctemplate['image']['process_image'] = 1;
		$ctemplate['image']['auto_generate_image_name'] = 0;
		$ctemplate['image']['type_generate_image_name'] = 'product_sku';
		if (isset($template->auto_generate_image_name_ext)) $ctemplate['image']['auto_generate_image_name_ext'] = $template->auto_generate_image_name_ext;
		else $ctemplate['image']['auto_generate_image_name_ext'] = 'jpg';
		$ctemplate['image']['change_case'] = 'none';
		$ctemplate['image']['empty_image'] = 0;
		$ctemplate['image']['keep_original'] = 0;
		$ctemplate['image']['convert_type'] = 'none';
		if (isset($template->save_images_on_server)) $ctemplate['image']['save_images_on_server'] = $template->save_images_on_server;
		else $ctemplate['image']['save_images_on_server'] = 0;
		$ctemplate['image']['full_resize'] = 0;
		$ctemplate['image']['full_width'] = '';
		$ctemplate['image']['full_height'] = '';
		$ctemplate['image']['thumb_check_filetype'] = 0;
		$ctemplate['image']['thumb_create'] = $template->thumb_create;
		$ctemplate['image']['thumb_extension'] = $template->thumb_extension;
		$ctemplate['image']['thumb_width'] = $template->thumb_width;
		$ctemplate['image']['thumb_height'] = $template->thumb_height;

		// Path settings
		if (isset($template->file_location)) $ctemplate['path']['file_location_product_images'] = JPath::clean($template->file_location, '/');
		else if (isset($template->file_location_product_images)) $ctemplate['path']['file_location_product_images'] = JPath::clean($template->file_location_product_images, '/');
		if (isset($template->file_location_category_images)) $ctemplate['path']['file_location_category_images'] = JPath::clean($template->file_location_category_images, '/');
		else $ctemplate['path']['file_location_category_images'] = '';
		if (isset($template->file_location_media)) $ctemplate['path']['file_location_media'] = JPath::clean($template->file_location_media, '/');
		else $ctemplate['path']['file_location_media'] = '';

		// Limit settings
		$ctemplate['limit']['use_system_limits'] = 0;
		$ctemplate['limit']['max_execution_time'] = $template->max_execution_time;
		$ctemplate['limit']['memory_limit'] = $template->memory_limit;
		$ctemplate['limit']['post_max_size'] = $template->post_max_size;
		$ctemplate['limit']['upload_max_filesize'] = $template->upload_max_filesize;

		// Replacement settings
		$ctemplate['replacement_import_fields']['_replace_type'] = array();

		// Import fields
		foreach ($template->fields as $field) {
			$ctemplate['import_fields']['_selected_name'][] = $field->field_name;
			$ctemplate['import_fields']['_default_value'][] = $field->field_default_value;
			$ctemplate['import_fields']['_process_field'][] = $field->published;
			$ctemplate['import_fields']['_combine_field'][] = 0;
		}

		// Send the converted template back
		return $ctemplate;
	}

	/**
	 * Convert an export template
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo 		Test manufacturer
	 * @todo		Test shopper group ID
	 * @see
	 * @access 		private
	 * @param
	 * @return 		array	containing the converted template
	 * @since 		3.0
	 */
	private function _exportTemplate($template) {

		$ctemplate = array();

		// Template settings
		$ctemplate['id'] = $template->template_id;
		$ctemplate['name'] = $template->template_name;

		// General settings
		$ctemplate['export_type'] = $template->template_type;
		if (isset($template->export_email) && $template->export_email) $ctemplate['general']['exportto'] = 'toemail';
		else $ctemplate['general']['exportto'] = 'todownload';
		if (isset($template->file_location_export_files)) $ctemplate['general']['localpath'] = JPath::clean($template->file_location_export_files, '/');
		else $ctemplate['general']['localpath'] = '';
		$ctemplate['general']['ftphost'] = '';
		$ctemplate['general']['ftpport'] = '';
		$ctemplate['general']['ftpusername'] = '';
		$ctemplate['general']['ftppass'] = '';
		$ctemplate['general']['ftproot'] = '';
		$ctemplate['general']['export_filename'] = $template->export_filename;
		$ctemplate['general']['export_file'] = $template->export_type;
		if ($template->export_site == 'froogle') $template->export_site = 'google';
		$ctemplate['general']['export_site'] = $template->export_site;
		$ctemplate['general']['field_delimiter'] = $template->field_delimiter;
		$ctemplate['general']['text_enclosure'] = $template->text_enclosure;
		$ctemplate['general']['category_separator'] = '/';
		$ctemplate['general']['include_column_headers'] = $template->include_column_headers;
		$ctemplate['general']['signature'] = 0;
		if (isset($template->export_frontend)) $ctemplate['general']['export_frontend'] = $template->export_frontend;
		else $ctemplate['general']['export_frontend'] = 0;
		$ctemplate['general']['collect_debug_info'] = $template->collect_debug_info;
		$ctemplate['general']['publish_state'] = $template->product_publish;
		$ctemplate['general']['recordstart'] = '';
		$ctemplate['general']['recordend'] = '';
		$ctemplate['general']['groupby'] = 1;
		if (isset($template->vm_itemid)) $ctemplate['general']['vm_itemid'] = $template->vm_itemid;
		else $ctemplate['general']['vm_itemid'] = '';
		if (isset($template->export_date_format)) $ctemplate['general']['export_date_format'] = $template->export_date_format;
		else $ctemplate['general']['export_date_format'] = 'd/m/Y H:i:s';
		$ctemplate['general']['export_price_format_decimal'] = 2;
		$ctemplate['general']['export_price_format_decsep'] = ',';
		$ctemplate['general']['export_price_format_thousep'] = '.';
		if (isset($template->add_currency_to_price)) $ctemplate['general']['add_currency_to_price'] = $template->add_currency_to_price;
		else $ctemplate['general']['add_currency_to_price'] = 0;

		// Order settings
		$ctemplate['order']['ordernostart'] = '';
		$ctemplate['order']['ordernoend'] = '';
		$ctemplate['order']['orderlist'] = '';
		$ctemplate['order']['orderdatestart'] = '';
		$ctemplate['order']['orderdateend'] = '';
		$ctemplate['order']['ordermdatestart'] = '';
		$ctemplate['order']['ordermdateend'] = '';
		$ctemplate['order']['orderstatus'][0] = '';
		$ctemplate['order']['orderpayment'][0] = '';
		$ctemplate['order']['order_address'] = '';
		$ctemplate['order']['manufacturer'][0] = '';
		$ctemplate['order']['ordercurrency'][0] = '';
		$ctemplate['order']['orderpricestart'] = '';
		$ctemplate['order']['orderpriceend'] = '';
		$ctemplate['order']['orderuser'][0] = '';
		$ctemplate['order']['orderproduct'][0] = '';

		// Order item settings
		$ctemplate['orderitem']['orderitemsnostart'] = '';
		$ctemplate['orderitem']['orderitemsnoend'] = '';
		$ctemplate['orderitem']['orderitemlist'] = '';
		$ctemplate['orderitem']['orderitemsdatestart'] = '';
		$ctemplate['orderitem']['orderitemsdateend'] = '';
		$ctemplate['orderitem']['orderitemsmdatestart'] = '';
		$ctemplate['orderitem']['orderitemsmdateend'] = '';
		$ctemplate['orderitem']['orderitemstatus'][0] = '';
		$ctemplate['orderitem']['orderitemcurrency'][0] = '';
		$ctemplate['orderitem']['orderitemspricestart'] = '';
		$ctemplate['orderitem']['orderitemspriceend'] = '';
		$ctemplate['orderitem']['orderitemproduct'][0] = '';

		// Product settings
		$ctemplate['product']['exportsef'] = 1;
		$ctemplate['product']['producturl_suffix'] = $template->producturl_suffix;
		$ctemplate['product']['featured'] = 0;
		$ctemplate['product']['use_joomfish'] = 0;
		$ctemplate['product']['joomfish_language'] = 1;
		$ctemplate['product']['productcategories'][0] = '';
		$ctemplate['product']['incl_subcategory'] = 0;
		$ctemplate['product']['productskufilter'] = '';
		$ctemplate['product']['pricequantitystartfrom'] = '';
		$ctemplate['product']['pricequantitystartto'] = '';
		$ctemplate['product']['pricequantityendfrom'] = '';
		$ctemplate['product']['pricequantityendto'] = '';
		$ctemplate['product']['stocklevelstart'] = '';
		$ctemplate['product']['stocklevelend'] = '';
		$ctemplate['product']['targetcurrency'] = '';
		$ctemplate['product']['shopper_group_id'][0] = $template->shopper_group_id;
		$ctemplate['product']['manufacturers'][0] = $template->manufacturer;

		// Multiple prices settings
		$ctemplate['multipleprices']['shopper_group_id'][0] = $template->shopper_group_id;

		// Product type names settings
		$ctemplate['producttypename']['producttypenames'] = '';

		// User info settings
		$ctemplate['userinfo']['userinfo_address'] = '';
		$ctemplate['userinfo']['vendors'][0] = '';
		$ctemplate['userinfo']['permissions'][0] = '';
		$ctemplate['userinfo']['userinfomdatestart'] = '';
		$ctemplate['userinfo']['userinfomdateend'] = '';

		// Layout settings
		$ctemplate['layout']['header'] = '';
		$ctemplate['layout']['body'] = '';
		$ctemplate['layout']['footer'] = '';

		// E-mail settings
		if (isset($template->export_email_addresses)) $ctemplate['email']['export_email_addresses'] = $template->export_email_addresses;
		else $ctemplate['email']['export_email_addresses'] = '';
		if (isset($template->export_email_addresses_cc)) $ctemplate['email']['export_email_addresses_cc'] = $template->export_email_addresses_cc;
		else $ctemplate['email']['export_email_addresses_cc'] = '';
		if (isset($template->export_email_addresses_bcc)) $ctemplate['email']['export_email_addresses_bcc'] = $template->export_email_addresses_bcc;
		else $ctemplate['email']['export_email_addresses_bcc'] = '';
		if (isset($template->export_email_subject)) $ctemplate['email']['export_email_subject'] = $template->export_email_subject;
		else $ctemplate['email']['export_email_subject'] = '';
		if (isset($template->export_email_body)) $ctemplate['email']['export_email_body'] = $template->export_email_body;
		else $ctemplate['email']['export_email_body'] = '';

		// Limit settings
		if (isset($template->use_system_limits)) $ctemplate['limit']['use_system_limits'] = $template->use_system_limits;
		else $ctemplate['limit']['use_system_limits'] = 0;
		$ctemplate['limit']['max_execution_time'] = $template->max_execution_time;
		$ctemplate['limit']['memory_limit'] = $template->memory_limit;

		// Replacement settings
		// Version 2.0 and 2.1 replacements are not field linked but template wide
		if ($template->replacement) {
			foreach ($template->replacement as $replacement) {
				$ctemplate['replacement_export_fields']['_replace_type'][] = $replacement->regex;
				if (isset($replacement->selected_name)) $ctemplate['replacement_export_fields']['_selected_name'][] = $replacement->selected_name;
				$ctemplate['replacement_export_fields']['_old_value'][] = $replacement->old_value;
				$ctemplate['replacement_export_fields']['_new_value'][] = $replacement->new_value;
			}
		}
		else $ctemplate['replacement_export_fields'] = array();

		// Export fields
		foreach ($template->fields as $field) {
			$ctemplate['export_fields']['_selected_name'][] = $field->field_name;
			$ctemplate['export_fields']['_column_header'][] = $field->field_column_header;
			$ctemplate['export_fields']['_default_value'][] = $field->field_default_value;
			$ctemplate['export_fields']['_process_field'][] = $field->published;
			$ctemplate['export_fields']['_combine_field'][] = 0;
			$ctemplate['export_fields']['_sort_field'][] = 0;
		}

		// Send the converted template back
		return $ctemplate;
	}

	/**
	 * Convert the log entries from the old version. Maximum 100 logs.
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		string	$version	the version to convert from
	 * @return 		bool	true if conversion is OK | false if conversion failed
	 * @since 		3.0
	 */
	private function _convertLog($version) {
		$db = JFactory::getDBO();
		$convert_maint = false;

		switch ($version) {
			case '1.5':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_logs (`id`, `userid`, `logstamp`, `action`, `action_type`, `records`, `run_id`) (SELECT *, id AS run_id FROM #__csvi_logs'.'_'.$this->_tag.' LIMIT 100)');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_CONVERTED');
					$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_log_details (`id`, `log_id`, `description`, `result`, `status`)
									(SELECT * FROM #__csvi_log_details'.'_'.$this->_tag.'
									WHERE log_id IN (SELECT `id` FROM #__csvivirtuemart_logs))');
					if ($db->query()) {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_CONVERTED');
						return true;
					}
					else $this->_results['messages'][] = $db->getErrorMsg();
				}
				else $this->_results['messages'][] = $db->getErrorMsg();
				// Convert maintenance tags
				$convert_maint = true;
				break;
			case '1.7':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_logs (`id`, `userid`, `logstamp`, `action`, `action_type`, `template_name`, `records`, `run_id`) (SELECT *, id AS run_id FROM #__csvi_logs'.'_'.$this->_tag.' LIMIT 100)');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_CONVERTED');
					$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_log_details (`id`, `log_id`, `description`, `result`, `status`)
									(SELECT * FROM #__csvi_log_details'.'_'.$this->_tag.'
									WHERE log_id IN (SELECT `id` FROM #__csvivirtuemart_logs))');
					if ($db->query()) {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_CONVERTED');
						return true;
					}
					else $this->_results['messages'][] = $db->getErrorMsg();
				}
				else $this->_results['messages'][] = $db->getErrorMsg();
				// Convert maintenance tags
				$convert_maint = true;
				break;
			case '2.0':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_logs (`id`, `userid`, `logstamp`, `action`, `action_type`, `template_name`, `records`, `run_id`) (SELECT *, id AS run_id FROM #__csvivirtuemart_logs'.'_'.$this->_tag.' LIMIT 100)');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_CONVERTED');
					$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_log_details (`id`, `log_id`, `description`, `result`, `status`)
									(SELECT * FROM #__csvivirtuemart_log_details'.'_'.$this->_tag.'
									WHERE log_id IN (SELECT `id` FROM #__csvivirtuemart_logs))');
					if ($db->query()) {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_CONVERTED');
						return true;
					}
					else $this->_results['messages'][] = $db->getErrorMsg();
				}
				else $this->_results['messages'][] = $db->getErrorMsg();
				// Convert maintenance tags
				$convert_maint = true;
				break;
			case '2.1':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_logs (`id`, `userid`, `logstamp`, `action`, `action_type`, `template_name`, `records`, `run_id`, `file_name`)
						(SELECT `id`, `userid`, `logstamp`, `action`, `action_type`, `template_name`, `records`, `file_name`, import_id as run_id FROM #__csvivirtuemart_logs'.'_'.$this->_tag.' LIMIT 100)');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_CONVERTED');
					$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_log_details
									(SELECT * FROM #__csvivirtuemart_log_details'.'_'.$this->_tag.'
									WHERE log_id IN (SELECT `id` FROM #__csvivirtuemart_logs))');
					if ($db->query()) {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_CONVERTED');
					}
					else {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_NOT_CONVERTED');
						$this->_results['messages'][] = $db->getErrorMsg();
					}
				}
				else {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_NOT_CONVERTED');
					$this->_results['messages'][] = $db->getErrorMsg();
				}
				// Convert maintenance tags
				$convert_maint = true;
				break;
			case '3.0':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_logs (SELECT * FROM #__csvivirtuemart_logs'.'_'.$this->_tag.' LIMIT 100)');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_CONVERTED');
					$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_log_details
									(SELECT * FROM #__csvivirtuemart_log_details'.'_'.$this->_tag.'
									WHERE log_id IN (SELECT `id` FROM #__csvivirtuemart_logs))');
					if ($db->query()) {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_CONVERTED');
					}
					else {
						$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_DETAIL_ENTRIES_NOT_CONVERTED');
						$this->_results['messages'][] = $db->getErrorMsg();
					}
				}
				else {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_ENTRIES_NOT_CONVERTED');
					$this->_results['messages'][] = $db->getErrorMsg();
				}
				break;
		}

		// Update the maintenance labels
		if ($convert_maint) {
			$db->setQuery("UPDATE `#__csvivirtuemart_logs` SET `action_type` = CONCAT(`action_type`, '_label') WHERE `action` = 'maintenance'");
			if ($db->query()) {
				$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_MAINT_ENTRIES_UPDATED');
			}
			else {
				$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_LOG_MAINT_ENTRIES_NOT_UPDATED');
				$this->_results['messages'][] = $db->getErrorMsg();
			}
		}
	}

	/**
	 * Convert the currency details
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		string	$version	the version to convert from
	 * @return
	 * @since 		3.0
	 */
	private function _convertCurrency($version) {
		$db = JFactory::getDBO();

		switch ($version) {
			case '1.7':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_currency (SELECT * FROM #__csvi_currency'.'_'.$this->_tag.')');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_CURRENCY_ENTRIES_CONVERTED');
					return true;
				}
				else $this->_results['messages'][] = $db->getErrorMsg();
				break;
			case '2.0':
			case '2.1':
			case '3.0':
				$db->setQuery('INSERT IGNORE INTO #__csvivirtuemart_currency (SELECT * FROM #__csvivirtuemart_currency'.'_'.$this->_tag.')');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_CURRENCY_ENTRIES_CONVERTED');
					return true;
				}
				else $this->_results['messages'][] = $db->getErrorMsg();
				break;
		}
	}

	/**
	 * Convert the settings from the old version
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		string	$version	the version to convert from
	 * @return
	 * @since 		3.0
	 */
	private function _convertSetting($version) {
		$db = JFactory::getDBO();

		switch ($version) {
			case '2.1':
			case '3.0':
				$db->setQuery('REPLACE INTO #__csvivirtuemart_settings (SELECT * FROM #__csvivirtuemart_settings'.'_'.$this->_tag.')');
				if ($db->query()) {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_SETTINGS_CONVERTED');
					return true;
				}
				else $this->_results['messages'][] = $db->getErrorMsg();
				break;
		}
	}

	/**
	 * Store the templates
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param		string	$version	the version to convert from
	 * @return
	 * @since 		3.0
	 */
	private function _storeTemplates($version) {
		$db = JFactory::getDBO();

		switch ($version) {
			case '1.5':
			case '1.7':
			case '2.0':
			case '2.1':
				$table = $this->getTable('csvivirtuemart_template_settings');

				foreach ($this->_templates as $template) {
					// Load the template
					$id = $template['id'];
					$table->load($id);

					// Insert the ID so it can be updated
					$db->setQuery('INSERT INTO '.$db->nameQuote('#__csvivirtuemart_template_settings').' (id) VALUES ('.$id.')');
					$db->query();

					// Bind al the data
					$bind = array();
					$bind['name'] = $template['name'];

					$bind['settings'] = json_encode($template);

					if (isset($template['import_type'])) $bind['type'] = 'import';
					else if (isset($template['export_type'])) $bind['type'] = 'export';

					$table->bind($bind);

					// Store the template
					if ($table->store()) {
						$this->_results['messages'][] = JText::sprintf('COM_CSVIVIRTUEMART_TEMPLATE_CONVERTED', $template['name']);
					}
					else {
						$this->_results['messages'][] = JText::sprintf('COM_CSVIVIRTUEMART_TEMPLATE_NOT_CONVERTED', $template['name']);
						$this->_results['messages'][] = $table->getErrorMsg();
					}
				}
				break;
			case '3.0':
				$q = 'INSERT IGNORE INTO #__csvivirtuemart_template_settings (SELECT * FROM #__csvivirtuemart_template_settings'.'_'.$this->_tag.')';
				$db->setQuery($q);
				if ($db->query()) $this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_TEMPLATES_CONVERTED');
				else {
					$this->_results['messages'][] = JText::_('COM_CSVIVIRTUEMART_TEMPLATES_NOT_CONVERTED');
					$this->_results['messages'][] = $db->getErrorMsg();
				}
				break;
		}
	}

	/**
	 * Proxy function for calling the update the available fields
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getAvailableFields() {
		// Get the logger class
		$csvilog = new CsviLog();
		JRequest::setVar('csvilog', $csvilog);
		$model = $this->getModel('Availablefields');
		$model->prepareAvailableFields();
		$model->getFillAvailableFields();
	}

	/**
	 * Proxy function for installing sample templates
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getSampleTemplates() {
		// Get the logger class
		$csvilog = new CsviLog();
		JRequest::setVar('csvilog', $csvilog);
		$model = $this->getModel('Maintenance');
		$model->getInstallDefaultTemplates();
	}

	/**
	 * Create a proxy for including other models
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function getModel($model) {
		return $this->getInstance($model, 'CsvivirtuemartModel');
	}

	/**
	 * Set the current version in the database
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.1
	 */
	private function _setVersion() {
		$db = JFactory::getDBO();
		$q = "INSERT IGNORE INTO #__csvivirtuemart_settings (id, params) VALUES (2, '".JText::_('COM_CSVIVIRTUEMART_CSVI_VERSION')."')
			ON DUPLICATE KEY UPDATE params = '".JText::_('COM_CSVIVIRTUEMART_CSVI_VERSION')."'";
		$db->setQuery($q);
		$db->query();
	}

	/**
	 * Get the current version in the database
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.2
	 */
	private function _getVersion() {
		$db = JFactory::getDBO();
		$q = "SELECT params
			FROM #__csvivirtuemart_settings
			WHERE id = 2";
		$db->setQuery($q);
		return $db->loadResult();
	}

	/**
	 * Translate version
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return 		string with the working version
	 * @since 		3.5
	 */
	private function _translateVersion() {
		$version = JRequest::getVar('version');

		switch ($version) {
			case '3.0':
			case '3.1':
			case '3.2':
			case '3.2.1':
			case '3.2.2':
			case '3.2.3':
			case '3.3':
			case '3.3.1':
			case '3.4':
			case '3.5':
			case '3.6':
			case '3.7':
			case '3.8':
			case '3.8.1':
			case '3.8.2':
			case '3.8.3':
				return '3.0';
				break;
			default:
				return $version;
		}
	}

	/**
	 * Move the temporary files
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.5
	 */
	private function _moveTmp() {
		// Load the libraries
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');

		// Set some folders
		$oldtmp = JPATH_CACHE.'/com_csvivirtuemart';
		$newtmp = CSVIPATH_TMP;

		// See if the CSVI VirtueMart cache folder exists
		if (JFolder::exists($oldtmp)) {
			// Move the data to the new location
			if (JFolder::move($oldtmp, $newtmp)) return true;
		}
		else {
			// Create the new temporary and debug folder exists
			JFolder::create($newtmp.'/debug');
		}
	}
}
?>