<?php
/**
 *---------------------------------------------------------------------------------------
 * @package      VP Conversion Tracking - Joomla! System Plugin
 * @subpackage   For VirtueMart 3+
 *---------------------------------------------------------------------------------------
 * @copyright    Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @authors      Abhishek Das
 * @email        info@virtueplanet.com
 * @link         https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
*/
defined ('_JEXEC') or die;

/**
* VP Conversion Tracking System Plugin
* 
* @package  VP Conversion Tracking
*/
class plgSystemVPConversionTracking extends JPlugin
{
	protected $app;
	
	private $_helper;
	private $_html;
	private $_checkForValidOrder;
	private $_pid;
	
	/**
	 * Constructor.
	 *
	 * @param   object  &$subject  The object to observe
	 * @param   array   $config    An optional associative array of configuration settings.
	 */
	function __construct(&$subject, $config) 
	{
		parent::__construct ($subject, $config);

		// Register VP Conversion Tracking Helper class
		JLoader::register('plgSystemVPConversionTrackingHelper', __DIR__ . '/helper.php');

		$this->app = empty($this->app) ? JFactory::getApplication() : $this->app;
		
		// Create an instance of our helper
		$this->_helper = plgSystemVPConversionTrackingHelper::getInstance();
		
		// Reset the flag
		$this->_checkForValidOrder = false;
		
		// Set default pid
		$this->_pid = 18;
	}

	/**
	 * After custom VirtueMart site controller
	 * 
	 * @param  string  $controller  Controller Class Name
	 * 
	 * @return  void
	 */
	public function onVmSiteController($controller)
	{
		if (!empty($controller) && strtolower($controller) == 'thankyou' && !class_exists('VirtueMartControllerThankyou'))
		{
			$file = VPCT_PATH . '/controllers/thankyou.php';

			if (file_exists($file))
			{
				// Register thank you page controller
				require($file);
			}
		}
	}

	/**
	 * After VirtueMart order confirmation
	 * 
	 * @param  object   $cart   VirtueMartCart object
	 * @param  array    $order  VirtueMart Order Array
	 * 
	 * @return  mixed  (bool/null/void)
	 */
	public function plgVmConfirmedOrder($cart, $order)
	{
		if (!$this->_helper->isCompatible())
		{
			return null;
		}
		
		// Set order data
		$this->_helper->setOrderData($order);
		
		// Raise flag to check for order completion
		$this->_checkForValidOrder = true;
	}
	
	/**
	 * After VirtueMart payment response received
	 * 
	 * @param  string   $html   HTML contents to be displayed
	 * 
	 * @return  mixed  (bool/null/void)
	 */
	public function plgVmOnPaymentResponseReceived(&$html)
	{
		if (!$this->_helper->isCompatible())
		{
			return null;
		}
		
		// Keep a track of payment plugin's html
		$this->_html = &$html;
		
		// Raise flag to check for order completion
		$this->_checkForValidOrder = true;
	}

	/**
	 * After VirtueMart payment cancelled by user
	 * 
	 * @return  mixed  (bool/null/void)
	 */
	public function plgVmOnUserPaymentCancel()
	{
		if (!$this->_helper->isCompatible())
		{
			return null;
		}
		
		// Clear order data from session
		$this->_helper->clearData();
	}
	
	/**
	* After initialise events
	* 
	* @return void
	*/
	public function onAfterInitialise()
	{
		if ($this->app->isAdmin())
		{
			return;
		}
		
		if ($this->app->getUserState('proopc.lastvisited.url'))
		{
			// Thank you page should not be considered as last visited page
			$this->app->setUserState('proopc.lastvisited.url', $this->app->getUserState('vpct.lastvisited.url'));
		}
		
		if ($this->params->get('router') > 0 && $this->app->get('sef', 0))
		{
			// Get the router
			$router   = $this->app->getRouter();
			$myRouter = new VPCTHelperRouter();

			// Attach the callback to the router
			$router->attachBuildRule(array($myRouter, 'buildRouteBefore'), $router::PROCESS_BEFORE);
			
			// Attach the callback to the router
			$router->attachBuildRule(array($myRouter, 'buildRouteAfter'), $router::PROCESS_AFTER);
			
			// Attach the callback to the router
			$router->attachParseRule(array($myRouter, 'parseRoute'));
		}
	}

	/**
	* After route events
	* 
	* @return void
	*/
	public function onAfterRoute()
	{
		if ($this->app->isAdmin())
		{
			if (!version_compare(JVERSION, '3.0.0', 'ge'))
			{
				if ($this->app->input->getCmd('plugin') == 'vpconversiontracking')
				{
					// Register dlk helper class
					JLoader::register('VPDownloadKeyHelper', __DIR__ . '/fields/vpdownloadkey/helper.php');
					
					$options = array(
						'manifest' => __DIR__ . DIRECTORY_SEPARATOR . 'vpconversiontracking.xml'
					);
					
					if ($this->app->input->getCmd('method') == 'validatedlk')
					{
						// Return validation result
						return VPDownloadKeyHelper::getInstance($options)->validate($this->params->get('pid', $this->_pid));
					}
					elseif ($this->app->input->getCmd('method') == 'revalidatedlk')
					{
						// Return validation result
						return VPDownloadKeyHelper::getInstance($options)->revalidate($this->params->get('pid', $this->_pid));
					}
				}
			}
		}
		
		if (!$this->_helper->isCompatible())
		{
			return;
		}
		
		// Reload internal variables
		$this->_helper->loadVars();
	}

	/**
	* After dispatch events
	* 
	* @return void
	*/
	public function onAfterDispatch()
	{
		if (!$this->_helper->isCompatible(true))
		{
			return;
		}

		if ($this->_checkForValidOrder && $this->_helper->isOrderCompleted())
		{
			// Set existing order data as valid
			$this->_helper->setOrderDataValid();
			
			// Finalize session before redirection
			$this->_helper->finalizeSession();
			
			// Display thank you page
			$this->_helper->showThankyouPage($this->_html);
		}
		
		// If HTML page view
		if ($this->_helper->isHTML())
		{
			// Initialise tracker
			$this->_helper->initialiseTracker();
		}
	}
	
	/**
	* After render events
	* 
	* @return void
	*/
	public function onAfterRender()
	{
		if (!$this->_helper->isCompatible())
		{
			return;
		}
		
		// Render conversion tracking scripts
		$this->_helper->renderTracker();
	}
	
	/**
	* Ajax dlk validation event
	* 
	* @return json
	*/
	public function onAjaxVPConversionTracking()
	{
		if ($this->app->isAdmin())
		{
			// Register dlk helper class
			JLoader::register('VPDownloadKeyHelper', __DIR__ . '/fields/vpdownloadkey/helper.php');
			
			$options = array(
				'manifest' => __DIR__ . DIRECTORY_SEPARATOR . 'vpconversiontracking.xml'
			);
			
			if ($this->app->input->getCmd('method') == 'validatedlk')
			{
				// Return validation result
				return VPDownloadKeyHelper::getInstance($options)->validate($this->params->get('pid', $this->_pid));
			}
			elseif ($this->app->input->getCmd('method') == 'revalidatedlk')
			{
				// Return validation result
				return VPDownloadKeyHelper::getInstance($options)->revalidate($this->params->get('pid', $this->_pid));
			}
		}
	}
	
	/**
	* On live update before downloading package
	* 
	* @param  string  $url
	* @param  string  $headers
	* 
	* @return void
	*/
	public function onInstallerBeforePackageDownload(&$url, &$headers)
	{
		// Register dlk helper class
		JLoader::register('VPDownloadKeyHelper', __DIR__ . '/fields/vpdownloadkey/helper.php');
		
		$options = array(
			'manifest' => __DIR__ . DIRECTORY_SEPARATOR . 'vpconversiontracking.xml'
		);
		
		return VPDownloadKeyHelper::getInstance($options)->addDlk($url, $headers);
	}
}