<?php
/**
 * @version        4.3.0
 * @package        Joomla
 * @subpackage     helpdeskpro Pro
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2013 - 2021 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
defined('_JEXEC') or die;

use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Plugin\CMSPlugin;

class plgSystemAutoCloseTicket extends CMSPlugin
{
	/**
	 * Protect access to articles
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function onAfterRoute()
	{
		if (!file_exists(JPATH_ROOT . '/components/com_helpdeskpro/helpdeskpro.php'))
		{
			return;
		}

		$lastRun   = (int) $this->params->get('last_run', 0);
		$now       = time();
		$cacheTime = 7200; // 2 hours

		if (($now - $lastRun) < $cacheTime)
		{
			return;
		}

		//Store last run time
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		$this->params->set('last_run', $now);
		$params = $this->params->toString();

		$query->update('#__extensions')
			->set('params = ' . $db->quote($params))
			->where('`element` = "autocloseticket"')
			->where('`folder` = "system"');

		try
		{
			// Lock the tables to prevent multiple plugin executions causing a race condition
			$db->lockTable('#__extensions');
		}
		catch (Exception $e)
		{
			// If we can't lock the tables it's too risk continuing execution
			return;
		}

		try
		{
			// Update the plugin parameters
			$result = $db->setQuery($query)->execute();
			$this->clearCacheGroups(array('com_plugins'), array(0, 1));
		}
		catch (Exception $exc)
		{
			// If we failed to execite
			$db->unlockTables();
			$result = false;
		}

		try
		{
			// Unlock the tables after writing
			$db->unlockTables();
		}
		catch (Exception $e)
		{
			// If we can't lock the tables assume we have somehow failed
			$result = false;
		}

		// Abort on failure
		if (!$result)
		{
			return;
		}

		// Require necessary libraries files
		require_once JPATH_ADMINISTRATOR . '/components/com_helpdeskpro/init.php';
		require_once JPATH_ROOT . '/components/com_helpdeskpro/helper/helper.php';

		$numberDay          = $this->params->get('number_days', 14);
		$config             = \OSSolution\HelpdeskPro\Site\Helper\Helper::getConfig();
		$closedTicketStatus = $config->closed_ticket_status;

		$currentDate = $db->quote(HTMLHelper::_('date', 'Now', 'Y-m-d H:i:s'));
		$query->clear()
			->update('#__helpdeskpro_tickets')
			->set('status_id = ' . (int) $closedTicketStatus)
			->where("DATEDIFF($currentDate , modified_date) >= " . (int) $numberDay)
			->where('status_id != ' . (int) $closedTicketStatus);
		$db->setQuery($query);
		$db->execute();
	}

	/**
	 * Clears cache groups. We use it to clear the plugins cache after we update the last run timestamp.
	 *
	 * @param   array $clearGroups  The cache groups to clean
	 * @param   array $cacheClients The cache clients (site, admin) to clean
	 *
	 * @return  void
	 *
	 * @since   2.0.4
	 */
	private function clearCacheGroups(array $clearGroups, array $cacheClients = array(0, 1))
	{
		$conf = JFactory::getConfig();

		foreach ($clearGroups as $group)
		{
			foreach ($cacheClients as $client_id)
			{
				try
				{
					$options = array(
						'defaultgroup' => $group,
						'cachebase'    => ($client_id) ? JPATH_ADMINISTRATOR . '/cache' :
							$conf->get('cache_path', JPATH_SITE . '/cache'),
					);
					$cache   = JCache::getInstance('callback', $options);
					$cache->clean();
				}
				catch (Exception $e)
				{
					// Ignore it
				}
			}
		}
	}
}
