<?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\View\Article;

use HelpdeskProHelperBootstrap;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use OSL\Utils\Database as DatabaseUtils;
use OSL\View\HtmlView;
use OSSolution\HelpdeskPro\Site\Helper\Helper as HelpdeskproHelper;
use OSSolution\HelpdeskPro\Site\Helper\Html as HelpdeskproHelperHtml;

defined('_JEXEC') or die;

/**
 * Class Html
 *
 * @property \OSSolution\HelpdeskPro\Site\Model\Article $model
 */
class Html extends HtmlView
{
	protected function beforeRender()
	{
		$this->item = $this->model->getData();

		if (empty($this->item->id))
		{
			throw new \Exception(Text::_('HDP_ARTICLE_NOT_FOUND'), 404);
		}

		$config = HelpdeskproHelper::getConfig();

		// Update hits
		$this->model->hits();

		if ($config->highlight_code)
		{
			HelpdeskproHelper::loadHighlighter();
		}

		// Pathway
		$pathway = $this->container->app->getPathway();

		// Get category title
		$fieldSuffix = HelpdeskproHelper::getFieldSuffix();

		$db    = $this->model->getDbo();
		$query = $db->getQuery(true);
		$query->select('title')
			->from('#__helpdeskpro_categories')
			->where('id = ' . $this->item->category_id);

		if ($fieldSuffix)
		{
			DatabaseUtils::getMultilingualFields($query, array('title'), $fieldSuffix);
		}
		$db->setQuery($query);
		$categoryTitle = $db->loadResult();
		$pathway->addItem($categoryTitle, Route::_('index.php?option=com_helpdeskpro&view=articles&filter_category_id=' . $this->item->category_id . '&Itemid=' . $this->Itemid));
		$pathway->addItem($this->item->title);

		// Handle page title
		$active = $this->container->app->getMenu()->getActive();
		$params = HelpdeskproHelperHtml::getViewParams($active, array('categories', 'articles', 'article'));

		if (!$params->get('page_title'))
		{
			$params->set('page_title', $this->item->title);
		}

		HelpdeskproHelperHtml::prepareDocument($params, $this->item);

		$this->bootstrapHelper = HelpdeskProHelperBootstrap::getInstance();
	}
}