<?php
namespace Pay4All\Pro\License;

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

/**
 * WP-Cron wiring for the 48-hour Pay4All licence recheck.
 *
 * The event only fires when `installation_secret` is set — an unregistered
 * install has nothing to sign with, so the cron would just log an error.
 * `ensure_scheduled()` is called both from `Activator::activate()` and
 * from every admin request so the schedule survives a manually cleared
 * cron table.
 */
final class Cron {

	public static function bootstrap() : void {
		add_filter( 'cron_schedules',     [ self::class, 'register_schedule' ] );
		add_action( 'init',               [ self::class, 'ensure_scheduled' ] );
		add_action( Constants::CRON_HOOK, [ self::class, 'run' ] );
	}

	public static function register_schedule( $schedules ) {
		if ( ! isset( $schedules['pay4all_pro_48h'] ) ) {
			$schedules['pay4all_pro_48h'] = [
				'interval' => Constants::CHECK_INTERVAL_SECONDS,
				'display'  => __( 'Pay4All PRO — toutes les 48 heures', 'pay4all-pro' ),
			];
		}
		return $schedules;
	}

	public static function ensure_scheduled() : void {
		if ( ! wp_next_scheduled( Constants::CRON_HOOK ) ) {
			wp_schedule_event( time() + 5 * MINUTE_IN_SECONDS, 'pay4all_pro_48h', Constants::CRON_HOOK );
		}
	}

	public static function unschedule() : void {
		$ts = wp_next_scheduled( Constants::CRON_HOOK );
		if ( $ts ) { wp_unschedule_event( $ts, Constants::CRON_HOOK ); }
	}

	public static function run() : void {
		try {
			LicenseManager::instance()->run_periodic_check( false );
		} catch ( \Throwable $e ) {
			Store::set_last_error( '[cron] ' . $e->getMessage() );
		}
	}
}
