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

use Joomla\CMS\HTML\HTMLHelper;
use JPagination;
use OSL\Model\ListModel;

defined('_JEXEC') or die;

class Categories extends ListModel
{
	/**
	 * Initialize the model, add new states
	 */
	protected function initialize()
	{
		$this->state->insert('filter_parent_id', 'int', 0)
			->insert('filter_category_type', 'int', 0);
	}

	/**
	 * Method to get categories data
	 *
	 * @access public
	 * @return array
	 */
	public function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->data))
		{
			$parent = (int) $this->state->filter_parent_id;
			$db     = $this->getDbo();
			$query  = $this->buildListQuery();
			$db->setQuery($query);
			$rows = $db->loadObjectList();

			$children = [];

			// first pass - collect children
			if (count($rows))
			{
				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', $parent, '', [], $children, 9999);
			$total = count($list);

			$this->pagination = new JPagination($total, $this->state->limitstart, $this->state->limit);

			// slice out elements based on limits
			$this->data = array_slice($list, $this->pagination->limitstart, $this->pagination->limit);
		}

		return $this->data;
	}

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

		$query->select('COUNT(b.id) AS total_tickets')
			->leftJoin('#__helpdeskpro_tickets AS b ON tbl.id = b.category_id')
			->group('tbl.id');

		if ($this->state->filter_category_type)
		{
			$query->where('category_type IN (0, ' . (int) $this->state->filter_category_type . ')');
		}

		return $query;
	}
}