<?php
/**
 * @file    includes/admin/class-mbs-pa-api-sync-scheduler.php
 * Registers and manages the daily mbs_pa_api_sync WP-Cron event.
 * @package MyBookShowroom
 * @since   1.1.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class MBS_PA_API_Sync_Scheduler {

	/** Canonical cron event name — never vary this string. */
	const CRON_HOOK = 'mbs_pa_api_sync';

	// ── Bootstrap ──────────────────────────────────────────────────────────────

	public function __construct() {
		// AUD-009: instantiated during init priority 10; a callback added to the
		// currently-running init/p10 bucket never fires (same bug as PLG-NEW-013).
		if ( did_action( 'init' ) || doing_action( 'init' ) ) {
			$this->register();
		} else {
			add_action( 'init', array( $this, 'register' ) );
		}
	}

	// ── Instance methods ───────────────────────────────────────────────────────

	/**
	 * Bind the cron callback to the event hook.
	 * Hooked to 'init' so it fires in all request contexts (WP-Cron fires on
	 * the front end, not just in wp-admin).
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( self::CRON_HOOK, array( $this, 'run_sync' ) );
	}

	/**
	 * Cron callback — instantiate MBS_PA_API_Sync and run it.
	 *
	 * @return void
	 */
	public function run_sync(): void {
		( new MBS_PA_API_Sync() )->run();
	}

	// ── Activation / deactivation ──────────────────────────────────────────────

	/**
	 * Schedule the daily cron event.
	 * Called from the plugin activation hook in bookshowroom.php.
	 *
	 * @return void
	 */
	public static function schedule(): void {
		// V2-D-042: Site-wide cron -- only schedule on main site in multisite.
		if ( ! is_multisite() || is_main_site() ) {
			if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
				wp_schedule_event( time(), 'daily', self::CRON_HOOK );
			}
		}
	}

	/**
	 * Clear the cron event.
	 * Called from the plugin deactivation hook in bookshowroom.php.
	 *
	 * @return void
	 */
	public static function unschedule(): void {
		wp_clear_scheduled_hook( self::CRON_HOOK );
	}
}
