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

defined('_JEXEC') or die;

use DateTimeZone;
use Joomla\CMS\Factory;
use OSL\Model\Model;
use OSSolution\HelpdeskPro\Site\Helper\Database as HelpdeskproHelperDatabase;
use OSSolution\HelpdeskPro\Site\Helper\Helper as HelpdeskproHelper;

class Report extends Model
{
	protected function initialize()
	{
		$this->state->insert('filter_date_range', 'int', 0);
	}

	/**
	 * Get ticket statistic data
	 *
	 * @return array
	 *
	 * @throws \Exception
	 */
	public function getData()
	{
		$filterDate = (int) $this->state->filter_date_range;
		$config     = $this->container->appConfig;
		$db         = $this->getDbo();
		$query      = $db->getQuery(true);

		$categories = HelpdeskproHelperDatabase::getAllCategories();

		//List of statuses
		$statuses = HelpdeskproHelperDatabase::getAllStatuses();

		//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);

		switch ($filterDate)
		{
			case 0: //Today		
				$date = Factory::getDate('now', $config->get('offset'));
				$date->setTime(0, 0, 0);
				$date->setTimezone(new DateTimeZone('UCT'));
				$fromDate = $date->toSql(true);
				$date     = Factory::getDate('now', $config->get('offset'));
				$date->setTime(23, 59, 59);
				$date->setTimezone(new DateTimeZone('UCT'));
				$toDate = $date->toSql(true);
				break;
			case 1: //This week
				$date   = Factory::getDate('now', $config->get('offset'));
				$monday = clone $date->modify(('Sunday' == $date->format('l')) ? 'Monday last week' : 'Monday this week');
				$monday->setTime(0, 0, 0);
				$monday->setTimezone(new DateTimeZone('UCT'));
				$fromDate = $monday->toSql(true);
				$sunday   = clone $date->modify('Sunday this week');
				$sunday->setTime(23, 59, 59);
				$sunday->setTimezone(new DateTimeZone('UCT'));
				$toDate = $sunday->toSql(true);
				break;
			case 2: //This month
				$date = Factory::getDate(date('Y-m-01'), $config->get('offset'));
				$date->setTime(0, 0, 0);
				$date->setTimezone(new DateTimeZone('UCT'));
				$fromDate = $date->toSql(true);

				//$date = Factory::getDate(date('Y-m-t'), $config->get('offset'));
				$date = Factory::getDate('now', $config->get('offset'));
				$date->setTime(23, 59, 59);
				$date->setTimezone(new DateTimeZone('UCT'));
				$toDate = $date->toSql(true);
				break;
			case 3: //This year
				$date = Factory::getDate(date('Y-01-01'), $config->get('offset'));
				$date->setTime(0, 0, 0);
				$date->setTimezone(new DateTimeZone('UCT'));
				$fromDate = $date->toSql(true);
				$date     = Factory::getDate(date('Y-12-31'), $config->get('offset'));
				$date->setTime(23, 59, 59);
				$date->setTimezone(new DateTimeZone('UCT'));
				$toDate = $date->toSql(true);
				break;
			case 4: //All
				$date = Factory::getDate(date('2012-01-01'), $config->get('offset'));
				$date->setTime(0, 0, 0);
				$date->setTimezone(new DateTimeZone('UCT'));
				$fromDate = $date->toSql(true);
				$date     = Factory::getDate(date('Y-12-31'), $config->get('offset'));
				$date->setTime(23, 59, 59);
				$date->setTimezone(new DateTimeZone('UCT'));
				$toDate = $date->toSql(true);
				break;
			default: //Date range, from "from date" to "to date";
				break;
		}

		foreach ($categories as $category)
		{
			$category->status = array();

			$query->clear()
				->select('status_id, COUNT(*) AS number_tickets')
				->from('#__helpdeskpro_tickets')
				->where('created_date >=' . $db->quote($fromDate))
				->where('created_date<=' . $db->quote($toDate))
				->where('category_id=' . (int) $category->id)
				->group('status_id');
			$db->setQuery($query);
			$tickets      = $db->loadObjectList();
			$totalTickets = 0;

			foreach ($tickets as $ticket)
			{
				$category->status[$ticket->status_id] = $ticket->number_tickets;
				$totalTickets += $ticket->number_tickets;
			}
			$category->total_tickets = $totalTickets;
		}

		foreach ($staffs as $staff)
		{
			$staff->status = array();

			$query->clear()
				->select('status_id, COUNT(*) AS number_tickets')
				->from('#__helpdeskpro_tickets')
				->where('created_date >=' . $db->quote($fromDate))
				->where('created_date<=' . $db->quote($toDate))
				->where('staff_id=' . (int) $staff->id)
				->group('status_id');
			$db->setQuery($query);
			$tickets      = $db->loadObjectList();
			$totalTickets = 0;

			foreach ($tickets as $ticket)
			{
				$staff->status[$ticket->status_id] = $ticket->number_tickets;
				$totalTickets += $ticket->number_tickets;
			}

			$staff->total_tickets = $totalTickets;

		}

		$manageTickets = array();

		foreach ($managers as $manager)
		{
			$manageTickets[$manager]         = array();
			$manageTickets[$manager]['name'] = $manager;
			$managedCategoryIds              = HelpdeskproHelper::getTicketCategoryIds($manager);

			$query->clear()
				->select('status_id, COUNT(*) AS number_tickets')
				->from('#__helpdeskpro_tickets')
				->where('created_date >=' . $db->quote($fromDate))
				->where('created_date<=' . $db->quote($toDate))
				->where('category_id IN (' . implode(',', $managedCategoryIds) . ')')
				->group('status_id');
			$db->setQuery($query);
			$tickets      = $db->loadObjectList();
			$totalTickets = 0;

			foreach ($tickets as $ticket)
			{
				$manageTickets[$manager][$ticket->status_id] = $ticket->number_tickets;
				$totalTickets += $ticket->number_tickets;
			}

			$manageTickets[$manager]['total_tickets'] = $totalTickets;
		}

		$data               = array();
		$data['statuses']   = $statuses;
		$data['categories'] = $categories;
		$data['staffs']     = $staffs;
		$data['managers']   = $manageTickets;

		return $data;
	}
}