<?php 
namespace WCQT\classes\com;

class Cron
{
	var $already_fiered = false;
	public function __construct()
	{
		add_action( 'wp_loaded', array($this,'check_schedule') );	//wp: fiered only when accessin frontend
		add_action( 'wcqt_cron_tick', array($this, 'on_tick' ));
		add_action( 'cron_schedules', array($this, 'cron_schedules' ));
	}
	function cron_schedules($schedules)
	{
		if(!isset($schedules["wcqt_1_minutes"]))
		{
			$schedules["wcqt_1_minutes"] = array(
			'interval' => 1*60, 
			'display' => __('Once every 1 Minute'));
		}
		if(!isset($schedules["wcqt_5_minutes"]))
		{
			$schedules["wcqt_5_minutes"] = array(
			'interval' => 5*60, 
			'display' => __('Once every 5 Minutes'));
		}
		if(!isset($schedules["wcqt_20_minutes"]))
		{
			$schedules["wcqt_20_minutes"] = array(
			'interval' => 20*60, 
			'display' => __('Once every 20 Minutes'));
		}
		if(!isset($schedules["wcqt_10_minutes"]))
		{
			$schedules["wcqt_3_days"] = array(
			'interval' => (1440*3)*60, 
			'display' => __('Once 3 Days'));
		}
		if(!isset($schedules["wcqt_1_second"]))
		{
			$schedules["wcqt_1_second"] = array(
			'interval' => 1, 
			'display' => __('[Debug] Once very 1 second'));
		}
		return $schedules;
	}
	function check_schedule() 
	{
		if($this->already_fiered)
			return;
		
		$this->already_fiered = true;
		$update_frequency = "wcqt_5_minutes";
		//Reminder
		/* Fo testing reason: uncomment the following line to reset the timer
			wp_clear_scheduled_hook( 'wcqt_cron_tick' );
			return; 
		*/
		if($update_frequency != 'never')
		{
			if ( !wp_next_scheduled( 'wcqt_cron_tick' ) ) 
			{
				wp_schedule_event( time(), $update_frequency, 'wcqt_cron_tick' ); //seconds
			}
			
		}
		else 
			wp_clear_scheduled_hook( 'wcqt_cron_tick' );
			
	}
	function on_tick()
	{
		global $wcqt_order_model;
		$wcqt_order_model->perform_cron_jobs();		
	}
}
?>