<?php
/**
 * Cronjob Class
 *
 * @package tripzzy
 */

namespace Tripzzy\Core\Helpers;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

use Tripzzy\Core\Traits\DataTrait;

if ( ! class_exists( 'Tripzzy\Core\Helpers\Cron' ) ) {
	/**
	 * Class For Cronjob.
	 *
	 * @since 1.0.0
	 */
	class Cron {
		use DataTrait;

		/**
		 * Initialize cronjob.
		 *
		 * @return void
		 */
		public static function init() {
			add_action( 'cron_schedules', array( __CLASS__, 'cron_schedules' ) ); // Register Schedule.
			add_action( 'tripzzy_update_start_dates', array( 'Tripzzy\Core\Helpers\Trip', 'update_start_dates' ) );
		}

		/**
		 * Add Tripzzy cron schedules.
		 *
		 * @param array $schedules List of WP scheduled cron jobs.
		 *
		 * @return array
		 */
		public static function cron_schedules( $schedules ) {
			$schedules['tz_monthly']     = array(
				'interval' => 2635200,
				'display'  => __( 'Monthly', 'tripzzy' ),
			);
			$schedules['tz_fifteendays'] = array(
				'interval' => 1296000,
				'display'  => __( 'Every 15 Days', 'tripzzy' ),
			);
			$schedules['tz_min']         = array(
				'interval' => MINUTE_IN_SECONDS,
				'display'  => __( 'Every minute', 'tripzzy' ),
			);
			return $schedules;
		}

		/**
		 * Create cron jobs (clear them first).
		 */
		public static function create() {
			// Clear cronjob.
			self::clear();
			$all_crons = self::get_crons();

			// Create cronjob.
			foreach ( $all_crons as $cron_schedule => $cron_hooks ) {
				foreach ( $cron_hooks as $cron_hook ) {
					if ( ! wp_next_scheduled( self::get_prefix( $cron_hook ) ) ) {
						wp_schedule_event( time(), $cron_schedule, self::get_prefix( $cron_hook ) );
					}
				}
			}
		}

		/**
		 * Clear Cronjob on Deactivation and activation.
		 *
		 * @since 1.3.4 Used self::get_crons() method.
		 * @since 1.0.0
		 */
		public static function clear() {
			$all_crons = array_merge( ...array_values( self::get_crons() ) );
			foreach ( $all_crons as $cron_hook ) {
				wp_clear_scheduled_hook( self::get_prefix( $cron_hook ) );
			}
		}

		/**
		 * Get the list of all Tripzzy cron hooks.
		 *
		 * @since 1.3.4
		 * @return array
		 */
		public static function get_crons() {
			$crons = array(
				'twicedaily' => array(
					'cleanup_sessions',
					'update_start_dates',
				),
				'tz_min'     => array(
					'minutely_check',
				),
			);

			$crons = apply_filters( 'tripzzy_filter_cron_schedules', $crons );
			return $crons;
		}

		/**
		 * Check Schedule Exists.
		 *
		 * @param string $hook Hook name which is triggered when scheduled.
		 * @since 1.3.7
		 * @return bool
		 */
		public static function schedule_hook_exists( $hook ) {
			return wp_next_scheduled( self::get_prefix( $hook ) );
		}
	}
}
