<?php

namespace Waypoint\Agent\Compat;

use Waypoint\Agent\Base\Thing;

class Rank_Math_Pro_Update_Guard extends Thing {

	public function attach_hooks(): void {
		add_action( 'admin_init', [ $this, 'maybe_suppress_update_chain' ], 0 );
	}

	/**
	 * Prevent RankMathPro\Updates::do_updates() from running during admin-ajax
	 * requests. The update chain calls check_ajax_referer() internally, which
	 * wp_die(-1, 403)s on any ajax request that isn't its own — killing every
	 * unrelated admin-ajax call site-wide. It is also self-perpetuating because
	 * the version option is written after the include returns, so the die means
	 * the update never records completion and re-runs on every subsequent request.
	 *
	 * On a normal admin page load wp_doing_ajax() is false, get_chain_id() skips
	 * the nonce check, and the chain completes fine. So the fix is not to block
	 * the update, but to stop it running during ajax — it then runs and completes
	 * on the next /wp-admin/ page load.
	 */
	public function maybe_suppress_update_chain(): void {
		if ( ! wp_doing_ajax() ) {
			return;
		}

		if ( ! class_exists( '\RankMathPro\Updates' ) ) {
			return;
		}

		global $wp_filter;

		foreach ( [ 'admin_init', 'init' ] as $hook ) {
			if ( empty( $wp_filter[ $hook ] ) ) {
				continue;
			}
			foreach ( $wp_filter[ $hook ]->callbacks as $priority => $callbacks ) {
				foreach ( $callbacks as $id => $cb ) {
					$fn = $cb['function'];
					if ( is_array( $fn )
						&& is_object( $fn[0] )
						&& $fn[0] instanceof \RankMathPro\Updates
						&& 'do_updates' === $fn[1]
					) {
						remove_action( $hook, $fn, $priority );
					}
				}
			}
		}
	}
}
