<?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\Factory;
use OSL\Container\Container;
use OSL\Model\Model;
use OSSolution\HelpdeskPro\Site\Helper\Database as HelpdeskproHelperDatabase;
use OSSolution\HelpdeskPro\Site\Helper\Helper as HelpdeskproHelper;

// no direct access
defined('_JEXEC') or die;

class Activities extends Model
{

	private $users;

	/**
	 * Constructor
	 *
	 * @param Container $container
	 * @param array     $config
	 */
	public function __construct(Container $container, $config = array())
	{
		$config['table'] = '#__helpdeskpro_tickets';

		parent::__construct($container, $config);

		$date = Factory::getDate('now', Factory::getConfig()->get('offset'));

		$this->state->insert('filter_user_id', 'int', 0)
			->insert('filter_start_date', 'string', $date->format('Y-m-d'))
			->insert('filter_start_hour', 'int', 0)
			->insert('filter_end_date', 'string', $date->format('Y-m-d'))
			->insert('filter_end_hour', 'int', 23);
	}

	/**
	 * Get activities data
	 *
	 * @return array
	 */
	public function getData()
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true);

		$now = Factory::getDate('now', Factory::getConfig()->get('offset'));

		if (empty($this->state->filter_start_date))
		{
			$this->state->filter_start_date = $now->format('Y-m-d');
		}

		if (empty($this->state->filter_end_date))
		{
			$this->state->filter_start_date = $now->format('Y-m-d');
		}

		if (empty($this->state->filter_end_hour))
		{
			$this->state->filter_end_hour = 23;
		}

		$startDate = Factory::getDate($this->state->filter_start_date . ' ' . $this->state->filter_start_hour . ':00:00', Factory::getConfig()->get('offset'));
		$endDate   = Factory::getDate($this->state->filter_end_date . ' ' . $this->state->filter_end_hour . ':59:59', Factory::getConfig()->get('offset'));

		$query->select('tbl.*, c.title AS category_title')
			->from('#__helpdeskpro_messages AS tbl')
			->innerJoin('#__helpdeskpro_tickets as t ON tbl.ticket_id = t.id')
			->innerJoin('#__helpdeskpro_categories as c ON t.category_id = c.id')
			->where('tbl.date_added >= ' . $db->quote($startDate->toSql()))
			->where('tbl.date_added <= ' . $db->quote($endDate->toSql()));

		if ($this->state->filter_user_id)
		{
			$query->where('tbl.user_id = ' . $this->state->filter_user_id);
		}
		else
		{
			$users = $this->getUsers();

			$userIds = array();

			foreach ($users as $user)
			{
				$userIds[] = $user->id;
			}

			$query->where('tbl.user_id IN (' . implode(',', $userIds) . ')');
		}

		$startHour = $startDate->format('G');
		$endHour   = $endDate->format('G');

		if ($startHour <= $endHour)
		{
			$query->where('HOUR(tbl.date_added) >= ' . $startHour)
				->where('HOUR(tbl.date_added) <= ' . $endHour);
		}
		else
		{
			$query->where('(HOUR(tbl.date_added) >= ' . $startHour . ' OR HOUR(tbl.date_added) <= ' . $endHour . ' )');
		}

		$query->order('tbl.id DESC');
		$db->setQuery($query);

		return $db->loadObjectList();
	}

	/**
	 * Get list of users used in the activities report
	 *
	 * @return array
	 */
	public function getUsers()
	{
		if (empty($this->users))
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true);

			$categories = HelpdeskproHelperDatabase::getAllCategories();

			//List of staffs
			$staffs = HelpdeskproHelperDatabase::getAllStaffs((int) HelpdeskproHelper::getConfigValue('staff_group_id'));

			//Get list of managers
			$managers = array();

			foreach ($categories as $category)
			{
				if ($category->managers)
				{
					$managers = array_merge($managers, explode(',', trim($category->managers)));
				}
			}

			$managers = array_unique($managers);

			$query->select('id')
				->from('#__users AS a')
				->innerJoin('#__user_usergroup_map AS b ON a.id = b.user_id ')
				->where('b.group_id IN (7, 8)');
			$db->setQuery($query);
			$superAdminIds = $db->loadColumn();

			$query->clear()
				->select('id, username')
				->from('#__users')
				->where('username IN ("' . implode('","', $managers) . '") OR id IN (' . implode(',', $superAdminIds) . ')');
			$db->setQuery($query);

			$this->users = array_merge($staffs, $db->loadObjectList());
		}

		return $this->users;
	}
}