<?php
/**
 * @package    Essentials for VirtueMart
 * @author     Abhishek Das <info@virtueplanet.com>
 * @copyright  Copyright (C) 2012-2024 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

/**
 * Class VMEssentialsController
 *
 * @since  1.6
 */
class VMEssentialsController extends JControllerLegacy
{
	/**
	 * Method to display a view.
	 *
	 * @param   boolean $cachable  If true, the view output will be cached
	 * @param   mixed   $urlparams An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
	 *
	 * @return  JController   This object to support chaining.
	 *
	 * @since    1.5
	 */
	public function display($cachable = false, $urlparams = false)
	{
		$app    = JFactory::getApplication();
		$params = $app->getParams('com_vmessentials');
		$view   = $app->input->getCmd('view', 'wishlist');
		$user   = JFactory::getUser();
		
		$app->input->set('view', $view);
		
		if ($view == 'wishlist')
		{
			if (!$params->get('enable_wishlist', 1))
			{
				$app->enqueueMessage(JText::_('COM_VMESSENTIALS_MSG_WISHLIST_DISABLED'), 'warning');
				$app->redirect(JUri::base());
				return false;
			}
			
			if ($user->get('guest') && !$params->get('guest_wishlist', 1))
			{
				$return = VMEssentialsHelperRoute::getRoute('wishlist');
				
				$app->enqueueMessage(JText::_('COM_VMESSENTIALS_MSG_WISHLIST_NEED_LOGIN'), 'warning');
				$app->redirect(JRoute::_('index.php?option=com_users&view=login&return=' . VMEssentialsHelperUtility::encode($return), false));
				return false;
			}
		}
		
		if ($view == 'compare' && !$params->get('enable_compare', 1))
		{
			$app->enqueueMessage(JText::_('COM_VMESSENTIALS_MSG_COMPARE_DISABLED'), 'warning');
			$app->redirect(JUri::base());
			return false;
		}

		parent::display($cachable, $urlparams);

		return $this;
	}
	
	protected function _checkToken()
	{
		$app    = JFactory::getApplication();
		$doc    = JFactory::getDocument();
		$input  = $app->input;
		$method = $input->getMethod();
		$method = !empty($method) ? $method : 'post';
		$valid  = JSession::checkToken($method);
		
		if (!$valid)
		{
			$format = strtoupper($doc->getType());
			
			if ($format == 'JSON')
			{
				$this->jsonReturn(array('error' => 1, 'msg' => JText::_('JINVALID_TOKEN')));
			}
			
			$referrer = $this->input->server->getString('HTTP_REFERER');
			
			if (!JUri::isInternal($referrer))
			{
				$referrer = 'index.php';
			}
			
			$app->enqueueMessage(JText::_('JINVALID_TOKEN_NOTICE'), 'warning');
			$app->redirect($referrer);
		}
		
		return $valid;
	}
	
	protected function jsonReturn($output = array()) 
	{
		return VMEssentialsHelperUtility::jsonReturn($output);
	}
}
