<?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\Model;

use OSL\Container\Container;
use OSL\Model\ListModel;
use OSL\Utils\Database as DatabaseUtils;
use OSSolution\HelpdeskPro\Site\Helper\Helper as HelpdeskProHelper;

defined('_JEXEC') or die;

class Articles extends ListModel
{
	protected $clearJoin = false;

	/**
	 * Constructor.
	 *
	 * @param   Container  $container
	 * @param   array      $options
	 */
	public function __construct(Container $container, $options = [])
	{

		$options['search_fields'] = ['tbl.id', 'tbl.title', 'tbl.text'];

		$options['remember_states'] = true;

		parent::__construct($container, $options);
	}

	/**
	 * Initialize the model, add new states
	 */
	protected function initialize()
	{
		$this->state->insert('id', 'int', 0);
	}

	/**
	 * Build the query object which is used to get list of records from database
	 *
	 * @return \JDatabaseQuery
	 */
	protected function buildListQuery()
	{
		$query = parent::buildListQuery();

		if ($fieldSuffix = HelpdeskProHelper::getFieldSuffix())
		{
			DatabaseUtils::getMultilingualFields($query, ['tbl.title'], $fieldSuffix);
		}

		$query->innerJoin('#__helpdeskpro_categories AS c ON tbl.category_id = c.id')
			->where('tbl.published = 1')
			->where('c.published = 1')
			->where('c.access IN (' . implode(',', $this->container->user->getAuthorisedViewLevels()) . ')');

		if ($this->state->id)
		{
			$query->where('tbl.category_id = ' . $this->state->id);
		}

		return $query;
	}
}