<?php
/**
 * Flywheel Auto-Updates module.
 *
 * Flywheel's managed-WP environment doesn't fire WP's normal auto-update cron
 * hooks, so plugins and themes flagged for auto-update never actually update.
 * This module hooks `wp_update_plugins` (which Flywheel DOES fire on its own
 * cron) and manually triggers `wp_maybe_auto_update`, which is WP's core
 * auto-update entry point.
 *
 * No settings — pure on/off. Default-on (matches the framework's default for
 * unknown slugs in `BW_Dev_Settings::is_module_enabled()`).
 *
 * Safe on non-Flywheel hosts: `wp_maybe_auto_update` is idempotent and will
 * no-op if WP's own cron already ran it this request.
 *
 * @package BW_Dev
 */

defined( 'ABSPATH' ) || exit;

class BW_Dev_Module_Flywheel_Auto_Updates implements BW_Dev_Module_Interface {

	public function slug(): string {
		return 'flywheel_auto_updates';
	}

	public function label(): string {
		return __( 'Flywheel Auto-Updates', 'bw-dev' );
	}

	public function group(): string {
		return 'core';
	}

	public function default_settings(): array {
		return array();
	}

	public function sanitize( array $data ): array {
		// No settings beyond the master on/off toggle on the Modules tab.
		return array();
	}

	public function register(): void {
		add_action( 'wp_update_plugins', array( $this, 'trigger_auto_update' ), 20 );
	}

	/**
	 * On Flywheel, `wp_update_plugins` is fired by their managed cron but
	 * `wp_maybe_auto_update` (the action core normally schedules) is not. Fire
	 * it ourselves so plugins/themes flagged for auto-update actually update.
	 *
	 * Guards:
	 * - wp_doing_cron(): only fire during cron, never on a live request.
	 * - doing_action('wp_maybe_auto_update'): re-entrancy guard so we never
	 *   trigger the action from inside its own callback chain.
	 */
	public function trigger_auto_update(): void {
		if ( ! wp_doing_cron() ) {
			return;
		}
		if ( doing_action( 'wp_maybe_auto_update' ) ) {
			return;
		}
		do_action( 'wp_maybe_auto_update' );
	}

	public function render_tab(): void {
		?>
		<p class="description">
			<?php esc_html_e( 'Enables WordPress auto-updates on Flywheel-hosted sites.', 'bw-dev' ); ?>
		</p>
		<p>
			<?php
			esc_html_e(
				'Flywheel\'s managed environment fires the wp_update_plugins cron event but skips wp_maybe_auto_update, so plugins and themes that are flagged for auto-update never actually update. This module hooks wp_update_plugins and manually triggers wp_maybe_auto_update so auto-updates work normally.',
				'bw-dev'
			);
			?>
		</p>
		<p>
			<?php esc_html_e( 'There are no settings — enable on the Modules tab and it just works. Safe on non-Flywheel hosts (the trigger is a no-op when core has already run it).', 'bw-dev' ); ?>
		</p>
		<?php
	}

	public function uninstall(): void {
		// No-op. No persisted state.
	}
}
