<?php
/**
 * @package            Joomla
 * @subpackage         Event Booking
 * @author             Tuan Pham Ngoc
 * @copyright          Copyright (C) 2010 - 2021 Ossolution Team
 * @license            GNU/GPL, see LICENSE.php
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use OSSolution\HelpdeskPro\Site\Helper\Route as RouteHelper;

/** @var \Composer\Autoload\ClassLoader $autoLoader */
$autoLoader = include JPATH_LIBRARIES . '/vendor/autoload.php';
$autoLoader->setPsr4('OSSolution\\HelpdeskPro\\Site\\', JPATH_ROOT . '/components/com_helpdeskpro');

/**
 * Routing class from com_eventbooking
 *
 * @since  2.8.1
 */
class HelpdeskproRouter extends JComponentRouterBase
{
	/**
	 * Build the route for the com_eventbooking component
	 *
	 * @param   array &$query  An array of URL arguments
	 *
	 * @return  array  The URL arguments to use to assemble the subsequent URL.
	 *
	 * @since   2.8.1
	 */
	public function build(&$query)
	{
		$segments = [];

		//Store the query string to use in the parseRouter method
		$queryArr = $query;

		//We need a menu item.  Either the one specified in the query, or the current active one if none specified
		if (empty($query['Itemid']))
		{
			$menuItem = $this->menu->getActive();
		}
		else
		{
			$menuItem = $this->menu->getItem($query['Itemid']);

			// If the given menu item doesn't belong to our component, unset the Itemid from query array
			if ($menuItem && $menuItem->component != 'com_helpdeskpro')
			{
				unset($query['Itemid']);
			}
		}

		if ($menuItem && empty($menuItem->query['view']))
		{
			$menuItem->query['view'] = '';
		}

		//Are we dealing with link to a article or articles view
		if ($menuItem
			&& isset($query['view'], $query['id'], $menuItem->query['id'])
			&& $menuItem->query['view'] == $query['view']
			&& $menuItem->query['id'] == intval($query['id'])
		)
		{
			unset($query['view'], $query['id'], $query['catid']);
		}

		$view  = isset($query['view']) ? $query['view'] : '';
		$id    = isset($query['id']) ? (int) $query['id'] : 0;
		$catId = isset($query['catid']) ? (int) $query['catid'] : 0;

		switch ($view)
		{
			case 'article':
				if ($id)
				{
					$segments[] = RouteHelper::getArticleAlias($id);
				}

				if ($catId)
				{
					$segments = array_merge(RouteHelper::getCategoriesPath($catId, 'alias'), $segments);
					unset($query['catid']);
				}

				unset($query['view'], $query['id']);
				break;
			case 'articles':
				if ($id)
				{
					$segments[] = RouteHelper::getCategoryAlias($id);
				}

				unset($query['view'], $query['id']);
				break;
		}

		if (count($segments))
		{
			$systemVariables = [
				'option',
				'Itemid',
				'search',
				'start',
				'limitstart',
				'limit',
				'format',
			];

			foreach ($systemVariables as $variable)
			{
				if (isset($queryArr[$variable]))
				{
					unset($queryArr[$variable]);
				}
			}

			$db      = Factory::getDbo();
			$dbQuery = $db->getQuery(true);

			$queryString   = $db->quote(http_build_query($queryArr));
			$segments      = array_map('Joomla\CMS\Application\ApplicationHelper::stringURLSafe', $segments);
			$segmentString = implode('/', $segments);
			$key           = $db->quote(md5($segmentString));
			$dbQuery->select('id')
				->from('#__helpdeskpro_urls')
				->where('md5_key = ' . $key);
			$db->setQuery($dbQuery);
			$urlId = (int) $db->loadResult();

			if (!$urlId)
			{
				$dbQuery->clear()
					->insert('#__helpdeskpro_urls')
					->columns($db->quoteName(['md5_key', 'query', 'segment']))
					->values(implode(',', [$key, $queryString, $db->quote($segmentString)]));
				$db->setQuery($dbQuery);
				$db->execute();
			}
		}

		return $segments;
	}

	/**
	 * Parse the segments of a URL.
	 *
	 * @param   array &$segments  The segments of the URL to parse.
	 *
	 * @return  array  The URL attributes to be used by the application.
	 * @throws  Exception
	 *
	 * @since   2.8.1
	 */
	public function parse(&$segments)
	{
		$vars = [];

		if (count($segments))
		{
			$db    = Factory::getDbo();
			$key   = md5(str_replace(':', '-', implode('/', $segments)));
			$query = $db->getQuery(true);
			$query->select('`query`')
				->from('#__helpdeskpro_urls')
				->where('md5_key = ' . $db->quote($key));
			$db->setQuery($query);
			$queryString = $db->loadResult();

			if ($queryString)
			{
				parse_str(html_entity_decode($queryString), $vars);
			}
			else
			{
				$method = strtoupper(Factory::getApplication()->input->getMethod());

				if ($method == 'GET')
				{
					throw new Exception('Page not found', 404);
				}
			}

			if (version_compare(JVERSION, '4.0.0-dev', 'ge'))
			{
				$segments = [];
			}
		}

		return $vars;
	}
}

/**
 * Events Booking router functions
 *
 * These functions are proxies for the new router interface
 * for old SEF extensions.
 *
 * @param   array &$query  An array of URL arguments
 *
 * @return  array  The URL arguments to use to assemble the subsequent URL.
 */
function HelpdeskproBuildRoute(&$query)
{
	$router = new HelpdeskproRouter();

	return $router->build($query);
}

function HelpdeskproParseRoute($segments)
{
	$router = new HelpdeskproRouter();

	return $router->parse($segments);
}
