<?php
/**
 * User info 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: userinfoimport.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
 *
 * @package CSVIVirtueMart
 * @todo 	format registerdate
 */
class CsvivirtuemartModelUserinfoimport extends CsvivirtuemartModelImportfile {

	// Private tables
	/** @var object contains the vm_user_info table */
	private $_vm_user_info = null;
	/** @var object contains the vm_shopper_vendor_xref table */
	private $_vm_shopper_vendor_xref = null;
	/** @var object contains the user table */
	private $_user = null;
	/** @var object contains the user aro table */
	private $_core_acl_aro = null;

	// Public variables
	/** @var integer contains the unique user ID string for a billing or shipping address */
	public $user_info_id = null;
	/** @var integer contains the unique Joomla user ID */
	public $user_id = null;
	/** @var integer contains the unique shopper group ID */
	public $shopper_group_id = null;
	/** @var integer contains the unique vendor ID */
	public $vendor_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		change cdate/mdate to use JDate
	 * @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
		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 'cdate':
								$this->$name = $this->_datafield;
								break;
							case 'mdate':
								$this->$name = $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 		Check to get hash secret from VM config
	 * @todo		Add a beter text for MISSING_REQUIRED_FIELDS
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getProcessRecord() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$authorize = JFactory::getACL();
	   	$newUsertype = 'Registered';
	   	$userdata = array();
	   	$hash_secret = "VirtueMartIsCool";
	   	jimport('joomla.user.helper');

		// See if we have a user_info_id
		if (empty($this->user_info_id)) {
			// No user_info_id, maybe we have user_id, address_type and address_type_name
			if ((!isset($this->user_id) && (!isset($this->user_email))) || !isset($this->address_type) || !isset($this->address_type_name)) {
				// No way to identify what needs to be updated, set error and return
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_MISSING_REQUIRED_FIELDS'));
				return false;
			}
		}
		// We have a user_info_id, do we have a user_id
		else {
			$q = "SELECT user_id FROM #__vm_user_info WHERE user_info_id = ".$db->Quote($this->user_info_id);
			$db->setQuery($q);
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_FIND_USER_ID_FROM_VM'), true);
			$this->user_id = $db->loadResult();
		}

		// Check for the user_info_id
		if (empty($this->user_info_id)) {
			// See if we have a user_id or user_email
			if (!isset($this->user_id) && isset($this->user_email)) {
				// We have an e-mail address, find the user_id
				$q = "SELECT id
					FROM #__users
					WHERE email = ".$db->Quote($this->user_email);
				$db->setQuery($q);
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_FIND_USER_ID_FROM_JOOMLA'), true);
				$this->user_id = $db->loadResult();
			}
			if ($this->user_id) {
				// if we have a user_id we can get the user_info_id
				$q = "SELECT user_info_id
					FROM #__vm_user_info
					WHERE user_id = ".$db->Quote($this->user_id)."
					AND address_type = ".$db->Quote($this->address_type)."
					AND address_type_name = ".$db->Quote($this->address_type_name);
				$db->setQuery($q);
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_FIND_USER_INFO_ID'), true);
				$this->user_info_id = $db->loadResult();
				if ($db->getAffectedRows() == 0) $this->user_info_id = null;
			}
		}

		// If it is a new Joomla user but no username is set, we must set one
		if ((!isset($this->user_id) || !$this->user_id) && !isset($this->username)) {
			$userdata['username'] = $this->user_email;
		}
		// Set the username
		else if (isset($this->username)) $userdata['username'] = $this->username;

		// Check if we have an encrypted password
		if (isset($this->password_crypt)) {
			$userdata['password'] = $this->password_crypt;
		}
		else if (isset($this->password)) {
			// Check if we have an encrypted password
			$salt		= JUserHelper::genRandomPassword(32);
			$crypt		= JUserHelper::getCryptedPassword($this->password, $salt);
			$password	= $crypt.':'.$salt;
			$userdata['password'] = $password;
		}

		// No user id, need to create a user if possible
		if (!isset($this->user_id)
			&& isset($this->user_email)
			&& isset($this->password)) {

			// Set the creation date
			$date = JFactory::getDate();
			$userdata['registerDate'] = $date->toMySQL();

			// Check if the user has set a usertype
			if (!isset($this->usertype)) $userdata['usertype'] = $newUsertype;
			else $userdata['usertype'] = $this->usertype;
		}
		else if (!isset($this->user_id)
			&& (!isset($this->user_email)
			|| !isset($this->password))) {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_NEW_USER_PASSWORD_EMAIL'));
			return false;
		}
		else {
			// Set the id
			$userdata['id'] = $this->user_id;
		}

		// Check if the user has set a group id
		if (!isset($this->gid)) $userdata['gid'] = $authorize->get_group_id( '', $newUsertype, 'ARO' );
		else $userdata['gid'] = $this->gid;

		// Only store the Joomla user if there is an e-mail address supplied
		if (isset($this->user_email)) {
			// Set the name
			if (isset($this->name)) $userdata['name'] = $this->name;
			else {
				$fullname = false;
				if (isset($this->first_name)) $fullname .= $this->first_name.' ';
				if (isset($this->last_name)) $fullname .= $this->last_name;
				if (!$fullname) $fullname = $this->user_email;
				$userdata['name'] = trim($fullname);

			}

			// Set the email
			if (isset($this->user_email)) $userdata['email'] = $this->user_email;

			// Set if the user is blocked
			if (isset($this->block)) $userdata['block'] = $this->block;

			// Set the sendEmail
			if (isset($this->sendemail)) $userdata['sendEmail'] = $this->sendemail;

			// Set the registerDate
			if (isset($this->registerdate)) $userdata['registerDate'] = $this->registerdate;

			// Set the lastvisitDate
			if (isset($this->lastvisitdate)) $userdata['lastvisitDate'] = $this->lastvisitdate;

			// Set the activation
			if (isset($this->activation)) $userdata['activation'] = $this->activation;

			// Set the params
			if (isset($this->params)) $userdata['params'] = $this->params;

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

			// Store/update the user
			if ($this->_user->store()) {
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_JOOMLA_USER_STORED'), true);
				// Get the new user ID
				$this->user_id = $this->_user->id;
				// Store it in the ARO table
				$this->_core_acl_aro->section_value = 'users';
				$this->_core_acl_aro->value = $this->user_id;
				$this->_core_acl_aro->order_value = 0;
				if (array_key_exists('name', $userdata)) $this->_core_acl_aro->name = $userdata['name'];
				$this->_core_acl_aro->hidden = 0;
				// Check if there is already an entry
				$this->_core_acl_aro->check();

				// Store the ACL
				if ($this->_core_acl_aro->store()) {
					$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_JOOMLA_USER_ARO_STORED'), true);
					// Check if there is already
					$q = "INSERT INTO #__core_acl_groups_aro_map VALUES (".$userdata['gid'].", '', ".$this->_core_acl_aro->id.")
						ON DUPLICATE KEY UPDATE aro_id = ".$this->_core_acl_aro->id;
					$db->setQuery($q);
					$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_JOOMLA_USER_ARO_MAP'), true);
					$db->query();
				}
				else $csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_JOOMLA_USER_ARO_NOT_STORED'), true);
			}
			else $csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_JOOMLA_USER_NOT_STORED'), true);
		}
		else $csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_DEBUG_JOOMLA_USER_SKIPPED'));

		// Set the modified date
		if (!isset($this->mdate) && empty($this->mdate)) $this->mdate = time();

		// Bind the VirtueMart user data
		$this->_vm_user_info->bind($this);

		// Store the VirtueMart user info
		if ($this->_vm_user_info->store()) {
			if ($this->queryResult() == 'UPDATE') $csvilog->AddStats('updated', JText::_('COM_CSVIVIRTUEMART_UPDATE_USERINFO'));
			else $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ADD_USERINFO'));
		}
		else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_USERINFO_NOT_ADDED', $this->_vm_user_info->getError()));

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

		// See if there is any shopper group information to be stored
		// user_id, vendor_id, shopper_group_id, customer number
		// Get the user_id
		if (!isset($this->user_id) && isset($this->_vm_user_info->user_info_id)) {
			$q = "SELECT user_id
				FROM #__vm_user_info
				WHERE user_info_id = ".$db->Quote($this->_vm_user_info->user_info_id);
			$db->setQuery($q);
			$this->user_id = $db->loadResult();
		}

		// Get the vendor_id
		if (empty($this->vendor_id) && isset($this->vendor_name)) {
			$q = "SELECT vendor_id
				FROM #__vm_vendor
				WHERE vendor_name = ".$db->Quote($this->vendor_name);
			$db->setQuery($q);
			$this->vendor_id = $db->loadResult();
			if (empty($this->vendor_id)) $this->vendor_id = $this->getVendorId();
		}
		else $this->vendor_id = $this->GetVendorId();

		// Get the shopper_group_id
		if (empty($this->shopper_group_id) && isset($this->shopper_group_name)) {
			$q = "SELECT shopper_group_id
				FROM #__vm_shopper_group
				WHERE shopper_group_name = ".$db->Quote($this->shopper_group_name);
			$db->setQuery($q);
			$this->shopper_group_id = $db->loadResult();
			if (empty($this->shopper_group_id)) $this->shopper_group_id = $this->GetDefaultShopperGroupID();
		}
		else if (!isset($this->shopper_group_id) && !isset($this->shopper_group_name)) $this->shopper_group_id = $this->GetDefaultShopperGroupID();

		// Bind the shopper group data
		$this->_vm_shopper_vendor_xref->bind($this);
		if ($this->_vm_shopper_vendor_xref->store()) {
			if ($this->queryResult() == 'UPDATE') $csvilog->AddStats('updated', JText::_('COM_CSVIVIRTUEMART_UPDATE_SHOPPER_GROUP'));
			else $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ADD_SHOPPER_GROUP'));
		}
		else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_SHOPPER_GROUP_NOT_ADDED', $this->_vm_shopper_vendor_xref->getError()));

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

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

	/**
	 * Load the user info related tables
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.0
	 */
	private function _loadTables() {
		$this->_vm_user_info = $this->getTable('vm_user_info');
		$this->_vm_shopper_vendor_xref = $this->getTable('vm_shopper_vendor_xref');
		$this->_user = $this->getTable('users');
		$this->_core_acl_aro = $this->getTable('core_acl_aro');
	}

	/**
	 * Cleaning the user info related tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function cleanTables() {
		$this->_vm_user_info->reset();
		$this->_vm_shopper_vendor_xref->reset();
		$this->_user->reset();
		$this->_core_acl_aro->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;
			}
		}
	}
}
?>