<?php
/*
 * @package Sj K2 Filter
 * @version 1.1.0
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @copyright (c) 2016 YouTech Company. All Rights Reserved.
 * @author YouTech Company http://www.smartaddons.com
 *
 */

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

jimport('joomla.application.component.controller');

JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');

class SJK2FilterControllerCron extends K2FilterController
{
	public function display($cachable = false, $urlparams = false) {
		header('Content-type: text/html; charset=ISO-8859-1');
		
		$params = JComponentHelper::getParams('com_sjk2filter');
		$indexing = (int) $params->get('indexing_cron', 1);
		$interval = (int) $params->get('indexing_interval', 900);
		$interval = $interval * 60;
		$cronkey = $params->get('indexing_cron_key', 'indexing');
		
		if(!$indexing) return;
		
		$db = JFactory::getDbo();
		$query = "SELECT updatetime FROM #__sjk2filter WHERE `name` = 'cron'";
		$db->setQuery($query);
		$updatetime = $db->loadResult();
		$updatetime = !$updatetime ? 0 : strtotime($updatetime);
		
		$key = JRequest::getVar('sjkey');
		$run = (($updatetime + $interval < time()) || ($key == $cronkey));
		
		if($run) {
			$now = date('Y-m-d H:i:s');
			$query = "
					INSERT INTO #__sjk2filter
					SET 
						`name` = 'cron',
						`updatetime` = ".$db->quote($now).",
						`value` = 1
					ON DUPLICATE KEY UPDATE
						`updatetime` = ".$db->quote($now).",
						`value` = 1
					";
			$db->setQuery($query);
			$db->query();
			//
			$helper = new SJK2FilterHelper();
			$helper->indexingData('cron');
		} else {
			$msg = JText::sprintf('The cron job will be run on %s', date('Y-m-d H:i:s', $updatetime + $interval));
			jexit($msg);
		}
	}
}