<?php
/**
 * @version        4.3.0
 * @package        Joomla
 * @subpackage     Helpdesk Pro
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2013 - 2021 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

namespace OSSolution\HelpdeskPro\Site\Helper;

use Joomla\CMS\Filesystem\File;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Table\Table;
use Joomla\Registry\Registry;
use OSL\Container\Container;

defined('_JEXEC') or die;

class Html
{
	/**
	 * Render ShowOn string
	 *
	 * @param array $fields
	 *
	 * @return string
	 */
	public static function renderShowOn($fields)
	{
		$output = [];

		$i = 0;

		foreach ($fields as $name => $values)
		{
			$i++;

			$values = (array) $values;

			$data = [
				'field'  => $name,
				'values' => $values,
				'sign'   => '=',
			];

			$data['op'] = $i > 1 ? 'AND' : '';

			$output[] = json_encode($data);
		}

		return '[' . implode(',', $output) . ']';
	}

	public static function buildCategoryDropdown($selected, $name = 'parent_id', $attr = null, $rows = [])
	{
		if (empty($rows))
		{
			$db    = Container::getInstance('com_helpdeskpro')->db;
			$query = $db->getQuery(true);
			$query->select('id, parent_id, title')
				->from('#__helpdeskpro_categories')
				->where('category_type IN (0, 1)')
				->where('published=1');
			$db->setQuery($query);
			$rows = $db->loadObjectList();
		}

		$children = [];

		if ($rows)
		{
			// first pass - collect children
			foreach ($rows as $v)
			{
				$pt   = (int) $v->parent_id;
				$list = @$children[$pt] ? $children[$pt] : [];
				array_push($list, $v);
				$children[$pt] = $list;
			}
		}

		$list      = HTMLHelper::_('menu.treerecurse', 0, '', [], $children, 9999, 0, 0);
		$options   = [];
		$options[] = HTMLHelper::_('select.option', '0', Text::_('HDP_SELECT_CATEGORY'));

		foreach ($list as $item)
		{
			$options[] = HTMLHelper::_('select.option', $item->id, '&nbsp;&nbsp;&nbsp;' . $item->treename);
		}

		return HTMLHelper::_('select.genericlist', $options, $name,
			[
				'option.text.toHtml' => false,
				'option.text'        => 'text',
				'option.value'       => 'value',
				'list.attr'          => $attr,
				'list.select'        => $selected]);
	}

	/**
	 * Function to render a common layout which is used in different views
	 *
	 * @param string $layout
	 * @param array  $data
	 *
	 * @return string
	 * @throws \Exception
	 */
	public static function loadCommonLayout($layout, $data = [])
	{
		$app       = Container::getInstance('com_helpdeskpro')->app;
		$themeFile = str_replace('/tmpl', '', $layout);

		if (File::exists($layout))
		{
			$path = $layout;
		}
		elseif (File::exists(JPATH_THEMES . '/' . $app->getTemplate() . '/html/com_helpdeskpro/' . $themeFile))
		{
			$path = JPATH_THEMES . '/' . $app->getTemplate() . '/html/com_helpdeskpro/' . $themeFile;
		}
		elseif (File::exists(JPATH_ROOT . '/components/com_helpdeskpro/View/' . $layout))
		{
			$path = JPATH_ROOT . '/components/com_helpdeskpro/View/' . $layout;
		}
		else
		{
			throw new \RuntimeException(Text::_('The given shared template path is not exist'));
		}

		// Start an output buffer.
		ob_start();
		extract($data);

		// Load the layout.
		include $path;

		// Get the layout contents.
		return ob_get_clean();
	}

	/**
	 * Get page params of the given view
	 *
	 * @param $active
	 * @param $views
	 *
	 * @return Registry
	 */
	public static function getViewParams($active, $views)
	{
		if ($active && isset($active->query['view']) && in_array($active->query['view'], $views))
		{
			return $active->getParams();
		}

		return new Registry();
	}

	/**
	 * Helper method to prepare meta data for the document
	 *
	 * @param Registry $params
	 *
	 * @param Table  $item
	 */
	public static function prepareDocument($params, $item = null)
	{
		$container = Container::getInstance('com_helpdeskpro');

		$document = $container->document;
		$config   = $container->appConfig;

		$siteNamePosition = $config->get('sitename_pagetitles');
		$pageTitle        = $params->get('page_title');

		if ($pageTitle)
		{
			if ($siteNamePosition == 0)
			{
				$document->setTitle($pageTitle);
			}
			elseif ($siteNamePosition == 1)
			{
				$document->setTitle($config->get('sitename') . ' - ' . $pageTitle);
			}
			else
			{
				$document->setTitle($pageTitle . ' - ' . $config->get('sitename'));
			}
		}

		if (!empty($item->meta_keywords))
		{
			$document->setMetaData('keywords', $item->meta_keywords);
		}
		elseif ($params->get('menu-meta_keywords'))
		{
			$document->setMetaData('keywords', $params->get('menu-meta_keywords'));
		}

		if (!empty($item->meta_description))
		{
			$document->setMetaData('description', $item->meta_description);
		}
		elseif ($params->get('menu-meta_description'))
		{
			$document->setDescription($params->get('menu-meta_description'));
		}

		if ($params->get('robots'))
		{
			$document->setMetaData('robots', $params->get('robots'));
		}
	}
}