<?php
/**
 *
 * Controller for the front end User maintenance
 *
 * @package	VirtueMart
 * @subpackage User
 * @author Oscar van Eijk
 * @link http://www.virtuemart.net
 * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 * VirtueMart is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * @version $Id: user.php 6355 2012-08-20 09:23:27Z Milbo $
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

// Load the controller framework
jimport('joomla.application.component.controller');

/**
 * VirtueMart Component Controller
 *
 * @package		VirtueMart
 */
class VirtueMartControllerUser extends JController
{

	public function __construct()
	{
		parent::__construct();
		$this->useSSL = VmConfig::get('useSSL',0);
		$this->useXHTML = false;
		VmConfig::loadJLang('com_virtuemart_shoppers',TRUE);
	}

	/**
	 * Override of display to prevent caching
	 *
	 * @return  JController  A JController object to support chaining.
	 */
	public function display(){

		$document = JFactory::getDocument();
		$viewType = $document->getType();
		$viewName = JRequest::getCmd('view', $this->default_view);
		$viewLayout = JRequest::getCmd('layout', 'default');

		$view = $this->getView($viewName, $viewType, '', array('base_path' => $this->basePath, 'layout' => $viewLayout));
		$view->assignRef('document', $document);

		$view->display();

		return $this;
	}

	function edit(){

	}

	function renderMail(){
		$document = JFactory::getDocument();
		$viewType = $document->getType();
		$viewName = JRequest::getCmd('view', $this->default_view);
		$viewLayout = JRequest::getCmd('layout', 'default');

		$view = $this->getView($viewName, $viewType, '', array('base_path' => $this->basePath, 'layout' => $viewLayout));
		$view->assignRef('document', $document);

		$view->renderMailLayout(false,JFactory::getUser()->email);

		return $this;
	}

	/**
	 * deprecated
	 */
	function editAddressST(){

		$view = $this->getView('user', 'html');

		$view->setLayout('edit_address');

		$ftask ='saveAddressST';
		$view->assignRef('fTask', $ftask);
		// Display it all
		$view->display();

	}

	/**
	 * This is for use in the cart, it calls a standard template for editing user adresses. It sets the task following into the form
	 * of the template to saveCartUser, the task saveCartUser just sets the right redirect in the js save(). This is done just to have the
	 * controll flow in the controller and not in the layout. The layout is everytime calling a standard joomla task.
	 *
	 * @author Max Milbers
	 */

	function editAddressCart(){

		$view = $this->getView('user', 'html');

		$view->setLayout('edit_address');

		$ftask ='savecartuser';
		$view->assignRef('fTask', $ftask);

		// Display it all
		$view->display();

	}

	/**
	 * This is for use in the checkout process, it is the same like editAddressCart, but it sets the save task
	 * to saveCheckoutUser, the task saveCheckoutUser just sets the right redirect. This is done just to have the
	 * controll flow in the controller and not in the layout. The layout is everytime calling a standard joomla task.
	 *
	 * @author Max Milbers
	 */
	function editAddressCheckout(){

		$view = $this->getView('user', 'html');

		$view->setLayout('edit_address');

		$ftask ='savecheckoutuser';
		$view->assignRef('fTask', $ftask);

		// Display it all
		$view->display();
	}

	/**
	 * This function is called from the layout edit_adress and just sets the right redirect back to the cart
	 * We use here the saveData(true) function, because within the cart shouldnt be done any registration.
	 *
	 * @author Max Milbers
	 */
	function saveCheckoutUser(){

		$msg = $this->saveData(true,VmConfig::get('reg_silent',0));

		//We may add here the option for silent registration.
		$this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=cart&task=checkout',$this->useXHTML,$this->useSSL), $msg );
	}

	function registerCheckoutUser(){
		if($this->checkCaptcha('index.php?option=com_virtuemart&view=user&task=editaddresscheckout&addrtype=BT') != FALSE) {
			$msg = $this->saveData(true,true);
			$this->setRedirect(JRoute::_( 'index.php?option=com_virtuemart&view=cart&task=checkout',$this->useXHTML,$this->useSSL ),$msg);
		}
	}

	/**
	 * This function is called from the layout edit_adress and just sets the right redirect back to the cart.
	 * We use here the saveData(true) function, because within the cart shouldnt be done any registration.
	 *
	 * @author Max Milbers
	 */
	function saveCartUser(){

		$addressType = vRequest::getString('address_type');
		if($addressType=='BT'){
			$msg = $this->saveData(true,VmConfig::get('reg_silent',0));
		} else {
			$msg = $this->saveData(false,false,true);
		}

		$this->setRedirect(JRoute::_( 'index.php?option=com_virtuemart&view=cart', FALSE ),$msg);
	}

	function registerCartuser(){
		if($this->checkCaptcha('index.php?option=com_virtuemart&view=user&task=editaddresscart&addrtype=BT') != FALSE) {
			$msg = $this->saveData(true, true);
			$this->setRedirect(JRoute::_('index.php?option=com_virtuemart&view=cart', FALSE) , $msg);
		}
	}


	/**
	 * This is the save function for the normal user edit.php layout.
	 * We use here directly the userModel store function, because this view is for registering also
	 * it redirects to the standard user view.
	 *
	 * @author Max Milbers
	 */
	function saveUser(){

		$layout = JRequest::getWord('layout','edit');
		if($this->checkCaptcha('index.php?option=com_virtuemart&view=user&layout='.$layout) != FALSE) {
			$msg = $this->saveData(true, true);
			$this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, FALSE), $msg );
		}

	}

	function saveAddressST(){

		$msg = $this->saveData(false,false,true);
		$layout = 'edit';// JRequest::getWord('layout','edit');
		$this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, FALSE), $msg );

	}

	/**
	 * Save the user info. The saveData function don't use the userModel store function for anonymous shoppers, because it would register them.
	 * We make this function private, so we can do the tests in the tasks.
	 *
	 * @author Max Milbers
	 * @author Valérie Isaksen
	 *
	 * @param boolean Defaults to false, the param is for the userModel->store function, which needs it to determine how to handle the data.
	 * @return String it gives back the messages.
	 */
	private function saveData($cart=false,$register=false, $onlyAddress=false) {
		$mainframe = JFactory::getApplication();
		$currentUser = JFactory::getUser();
		$msg = '';

		$data = JRequest::get('post');

		if(empty($data['address_type'])){
			$data['address_type'] = vRequest::getCmd('addrtype','BT');
		}

		if($currentUser->guest!=1 || $register){
			$userModel = VmModel::getModel('user');

			if(!$cart){
				// Store multiple selectlist entries as a ; separated string
				if (array_key_exists('vendor_accepted_currencies', $data) && is_array($data['vendor_accepted_currencies'])) {
					$data['vendor_accepted_currencies'] = implode(',', $data['vendor_accepted_currencies']);
				}

				$data['vendor_store_name'] = JRequest::getVar('vendor_store_name','','post','STRING',JREQUEST_ALLOWHTML);
				$data['vendor_store_desc'] = JRequest::getVar('vendor_store_desc','','post','STRING',JREQUEST_ALLOWHTML);
				$data['vendor_terms_of_service'] = JRequest::getVar('vendor_terms_of_service','','post','STRING',JREQUEST_ALLOWHTML);
				$data['vendor_letter_css'] = JRequest::getVar('vendor_letter_css','','post','STRING',JREQUEST_ALLOWHTML);
				$data['vendor_letter_header_html'] = JRequest::getVar('vendor_letter_header_html','','post','STRING',JREQUEST_ALLOWHTML);
				$data['vendor_letter_footer_html'] = JRequest::getVar('vendor_letter_footer_html','','post','STRING',JREQUEST_ALLOWHTML);
			}

			//It should always be stored
			if($onlyAddress){
				$ret = $userModel->storeAddress($data);
			} else {
				$ret = $userModel->store($data);
			}
			if(!$onlyAddress and $currentUser->guest==1){
				$msg = (is_array($ret)) ? $ret['message'] : $ret;
				$usersConfig = JComponentHelper::getParams( 'com_users' );
				$useractivation = $usersConfig->get( 'useractivation' );

				if (is_array($ret) and $ret['success'] and !$useractivation) {
					// Username and password must be passed in an array
					$credentials = array('username' => $ret['user']->username,
			  					'password' => $ret['user']->password_clear
					);
					$return = $mainframe->login($credentials);
				} else if(VmConfig::get('oncheckout_only_registered',0)){
					$layout = JRequest::getWord('layout','edit');
					$this->redirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, FALSE), $msg );
				}

			}

		}

		if(!class_exists('VirtueMartCart')) require(JPATH_VM_SITE.DS.'helpers'.DS.'cart.php');
		$cart = VirtueMartCart::getCart();

		$cart->saveAddressInCart($data, $data['address_type']);

		return $msg;
	}



	/**
	 * Editing a user address was cancelled when called from the cart; return to the cart
	 *
	 * @author Oscar van Eijk
	 */
	function cancelCartUser(){

		$this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=cart', FALSE)  );
	}

	/**
	 * Editing a user address was cancelled during chaeckout; return to the cart
	 *
	 * @author Oscar van Eijk
	 */
	function cancelCheckoutUser(){
		$this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=cart&task=checkout',$this->useXHTML,$this->useSSL) );
	}

	/**
	 * Action cancelled; return to the previous view
	 *
	 * @author Oscar van Eijk
	 */
	function cancel()
	{
		$return = JURI::base();
		$this->setRedirect( $return );
	}


	function removeAddressST(){

		$virtuemart_userinfo_id = JRequest::getVar('virtuemart_userinfo_id');

		//Lets do it dirty for now
		$userModel = VmModel::getModel('user');
		$userModel->removeAddress($virtuemart_userinfo_id);

		$layout = JRequest::getWord('layout','edit');
		$this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, $this->useXHTML,$this->useSSL) );
	}

	/**
	 * Check the Joomla ReCaptcha Plg
	 *
	 * @author Maik Künnemann
	 */
	function checkCaptcha($retUrl){
		if(JFactory::getUser()->guest==1 and VmConfig::get ('reg_captcha')){
			$recaptcha = vRequest::getVar ('recaptcha_response_field');
			JPluginHelper::importPlugin('captcha');
			$dispatcher = JDispatcher::getInstance();
			$res = $dispatcher->trigger('onCheckAnswer',$recaptcha);
			if(!$res[0]){
				$data = vRequest::getPost();
				$data['address_type'] = vRequest::getVar('addrtype','BT');
				if(!class_exists('VirtueMartCart')) require(JPATH_VM_SITE.DS.'helpers'.DS.'cart.php');
				$cart = VirtueMartCart::getCart();
				$cart->saveAddressInCart($data, $data['address_type']);
				$errmsg = vmText::_('PLG_RECAPTCHA_ERROR_INCORRECT_CAPTCHA_SOL');
				$this->setRedirect (JRoute::_ ($retUrl . '&captcha=1', FALSE), $errmsg);
				return FALSE;
			} else {
				return TRUE;
			}
		} else {
			return TRUE;
		}
	}

}
// No closing tag
