<?php

declare( strict_types=1 );

namespace StrykeWP\Core;

use StrykeWP\Modules\Connector\ApiLogger;
use StrykeWP\Modules\Backup\BackupSettings;

/**
 * Centralises WP-Cron management for STRYKE WP.
 *
 * Registers custom cron intervals (stryke_weekly, stryke_monthly) at Core
 * level so they are available on every request — including non-admin cron
 * requests — regardless of which modules are enabled.
 *
 * Previously, these schedules were registered inside BackupAdmin::register_hooks()
 * which was only called in admin or DOING_CRON context. Moving them here
 * ensures they are always available when WordPress resolves intervals.
 *
 * @package StrykeWP\Core
 */
final class CronManager {

	// -----------------------------------------------------------------------
	// Hook Registration
	// -----------------------------------------------------------------------

	/**
	 * Registers the cron_schedules filter.
	 * Called from stryke_wp_init() so it runs on every request.
	 *
	 * @return void
	 */
	public function register_hooks(): void {
		add_filter( 'cron_schedules', [ $this, 'add_custom_schedules' ] );
	}

	// -----------------------------------------------------------------------
	// Custom Schedules
	// -----------------------------------------------------------------------

	/**
	 * Adds STRYKE-specific cron intervals to WordPress.
	 *
	 * @param array<string, array<string, mixed>> $schedules Existing WP-Cron schedules.
	 * @return array<string, array<string, mixed>>
	 */
	public function add_custom_schedules( array $schedules ): array {
		$schedules['stryke_weekly'] = [
			'interval' => WEEK_IN_SECONDS,
			'display'  => esc_html__( 'Wöchentlich (STRYKE)', 'stryke-wp' ),
		];

		$schedules['stryke_monthly'] = [
			'interval' => MONTH_IN_SECONDS,
			'display'  => esc_html__( 'Monatlich (STRYKE)', 'stryke-wp' ),
		];

		return $schedules;
	}

	// -----------------------------------------------------------------------
	// Cleanup
	// -----------------------------------------------------------------------

	/**
	 * Clears all STRYKE WP cron hooks.
	 *
	 * Called from Installer::deactivate(). Static so it can be called without
	 * an instance (activation hooks fire before plugins_loaded, so no DI
	 * container is available there).
	 *
	 * @return void
	 */
	public static function clear_all(): void {
		wp_clear_scheduled_hook( ApiLogger::CRON_HOOK );
		wp_clear_scheduled_hook( BackupSettings::CRON_HOOK );
	}
}
