<?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\Model\ListModel;
use OSL\Utils\Database as DatabaseUtils;
use Ossolution\HelpdeskPro\Site\Helper\Helper as HelpdeskproHelper;

defined('_JEXEC') or die;

class Categories extends ListModel
{

	/**
	 * Clear join clause for getTotal method
	 *
	 * @var bool
	 */
	protected $clearJoin = false;

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

		$query->select('COUNT(b.id) AS total_articles')
			->innerJoin('#__helpdeskpro_articles AS b ON tbl.id = b.category_id')
			->where('tbl.published = 1')
			->where('tbl.access IN (' . implode(',', $user->getAuthorisedViewLevels()) . ')')
			->where('b.published = 1')
			->group('tbl.id');


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

		return $query;
	}

	/**
	 * Get list of articles belong to each category, max 10 articles per category
	 *
	 * @param array $rows
	 */
	protected function beforeReturnData($rows)
	{
		$db          = $this->getDbo();
		$query       = $db->getQuery(true);
		$fieldSuffix = HelpdeskproHelper::getFieldSuffix();

		$query->select('id, title')
			->from('#__helpdeskpro_articles')
			->order('ordering');

		if ($fieldSuffix)
		{
			DatabaseUtils::getMultilingualFields($query, ['title'], $fieldSuffix);
		}

		foreach ($rows as $row)
		{
			$query->where('category_id = ' . $row->id)
				->where('published = 1');
			$db->setQuery($query, 0, 10);
			$row->articles = $db->loadObjectList();

			$query->clear('where');
		}
	}
}