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

defined('_JEXEC') or die;

use \Joomla\CMS\MVC\Controller\BaseController;
use \Joomla\CMS\Factory;
use \Joomla\CMS\Language\Text;

// Access check.
if (!Factory::getUser()->authorise('core.manage', 'com_vpem'))
{
	throw new Exception(Text::_('JERROR_ALERTNOAUTHOR'));
}

// Import all dependencies
JLoader::import('joomla.application.component.controller');

// Register all component classes
JLoader::registerPrefix('Vpem', JPATH_COMPONENT_ADMINISTRATOR);

// Register required dependencies
JLoader::register('VpemHelper', JPATH_COMPONENT_ADMINISTRATOR . '/helpers/vpem.php');
JLoader::register('VmConfig',   JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');

if (!class_exists('VmConfig'))
{
	throw new Exception('VirtueMart component not found.');
}

// Initialise VirtueMart
VmConfig::loadConfig();

// Check if the system plugin is enabled
if (!JPluginHelper::isEnabled('system', 'vpem'))
{
	Factory::getApplication()->enqueueMessage('Please enabled "System - VP Email Manager" plugin.', 'error');
}

// Check for download key
$params      = JComponentHelper::getParams('com_vpem');
$downloadKey = $params->get('download_key', '');
$downloadKey = $downloadKey ? trim($downloadKey) : null;

if (empty($downloadKey))
{
	Factory::getApplication()->enqueueMessage('Please add your <b>Download Key</b> in <b>VP Email Manager Configuration</b> to validate your copy and to receive Live Updates in future.', 'info');
}

// Register and check shopFunctionsF class override 
JLoader::register('shopFunctionsF',     JPATH_SITE . '/components/com_virtuemart/helpers/shopfunctionsf.php');
JLoader::register('shopFunctionsFTest', JPATH_SITE . '/plugins/system/vpem/helpers/shopfunctionsftest.php');

if (!class_exists('shopFunctionsFTest') || !shopFunctionsFTest::isVpemOverride())
{
	Factory::getApplication()->enqueueMessage('shopFunctionsF class override is not working. VP Email Manager can not handle VirtueMart emails.', 'error');
}

// Check if override system is working fine
if (!class_exists('shopFunctionsFTest') || !shopFunctionsFTest::isVpemOverride())
{
	Factory::getApplication()->enqueueMessage('shopFunctionsF override failed. You must be having some other extension which is already overriding shopFunctionsF class.', 'error');
}

// Get controller, execute assigned task and redirect
$controller = BaseController::getInstance('Vpem');

$controller->execute(Factory::getApplication()->input->get('task'));
$controller->redirect();
