<?php

namespace Ugcify\License;

defined( 'ABSPATH' ) || exit;

/**
 * Schedules and handles the periodic license revalidation cron job.
 *
 * Schedule: once weekly (custom 'weekly' interval = 604800 seconds).
 *
 * @since 1.1.0
 * @package Ugcify\License
 */
class LicenseCron {

	/**
	 * WordPress cron action hook name.
	 */
	const HOOK = 'ugcify_license_revalidate';

	/**
	 * WP cron recurrence slug.
	 */
	const INTERVAL = 'weekly';

	/**
	 * Register the WordPress action that fires when the cron event runs, and
	 * add the custom weekly schedule if not already registered.
	 *
	 * Must be called on every page load (e.g. from plugins_loaded) so the
	 * callback is available when WP-Cron executes the event.
	 */
	public static function register_hook(): void {
		add_filter( 'cron_schedules', array( __CLASS__, 'add_weekly_schedule' ) );
		add_action( self::HOOK, array( __CLASS__, 'handle' ) );
	}

	/**
	 * Add a 'weekly' cron schedule if WordPress does not already define one.
	 *
	 * @param array $schedules Existing cron schedules.
	 * @return array
	 */
	public static function add_weekly_schedule( $schedules ) {
		if ( ! isset( $schedules['weekly'] ) ) {
			$schedules['weekly'] = array(
				'interval' => 604800,
				'display'  => __( 'Once Weekly', 'ugcify' ),
			);
		}
		return $schedules;
	}

	/**
	 * Schedule the cron event if it is not already registered.
	 *
	 * Safe to call multiple times — wp_schedule_event is skipped when the
	 * event is already scheduled.
	 */
	public static function schedule(): void {
		if ( ! \wp_next_scheduled( self::HOOK ) ) {
			\wp_schedule_event( time(), self::INTERVAL, self::HOOK );
		}
	}

	/**
	 * Remove the scheduled cron event.
	 *
	 * Called from the plugin deactivation hook so unused cron slots are not
	 * left behind in wp_options cron list.
	 */
	public static function clear_schedule(): void {
		$timestamp = \wp_next_scheduled( self::HOOK );
		if ( $timestamp ) {
			\wp_unschedule_event( $timestamp, self::HOOK );
		}
	}

	/**
	 * Cron callback — delegates to Licensing::run_remote_revalidation().
	 */
	public static function handle(): void {
		Licensing::run_remote_revalidation();
	}
}
