<?php
/**
* @version 1.0.0
* @package RStickets! 1.0.0
* @copyright (C) 2007-2008 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// DIE()
defined('_JEXEC') or die('Restricted access');

if ($T_SETTINGS['Autoclose_Email_Interval'] == 0 && $T_SETTINGS['Autoclose_Interval'] == 0) return;

$T_SETTINGS['Autoclose_Cron_Lastcheck'] = time();
$db = JFactory::getDBO();
$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Autoclose_Cron_Lastcheck']."' WHERE `setting`='Autoclose_Cron_Lastcheck'");
$db->query();

$db->setQuery("SELECT `#__rstickets_ticket_message`.`TicketId`,`#__rstickets_tickets`.`TicketAutocloseSent` FROM `#__rstickets_ticket_message` LEFT JOIN `#__rstickets_tickets` ON (`#__rstickets_tickets`.`TicketId`=`#__rstickets_ticket_message`.`TicketId`) WHERE `#__rstickets_tickets`.`TicketStatus`!='closed' AND `#__rstickets_tickets`.`TicketAutocloseSent` > 0 AND `#__rstickets_tickets`.`TicketAutocloseSent` + '".($T_SETTINGS['Autoclose_Interval']*86400)."' <= '".time()."' GROUP BY `#__rstickets_ticket_message`.`TicketId` HAVING `#__rstickets_tickets`.`TicketAutocloseSent` > MAX(`#__rstickets_ticket_message`.`TicketTime`) ORDER BY `#__rstickets_ticket_message`.`TicketTime` DESC");

$db->query();

if ($db->getNumRows() > 0)
{
	$rows = $db->loadAssocList();
	$update_array = array();
	foreach ($rows as $row)
		$update_array[] = $row['TicketId'];

	$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketStatus`='closed' WHERE `TicketId` IN (".implode(',',$update_array).")");
	$db->query();
}
?>