<?php
/**
 * Heartbeat optimizer.
 *
 * Controls the WordPress Heartbeat API frequency to reduce
 * server load and improve admin performance.
 *
 * @package MonitorCat\Modules\Speed\Optimizer
 */

declare(strict_types=1);

namespace MonitorCat\Modules\Speed\Optimizer;

defined( 'ABSPATH' ) || exit;

use MonitorCat\Settings;

/**
 * Optimizes WordPress Heartbeat API settings.
 */
final class HeartbeatOptimizer {

	/**
	 * Plugin settings.
	 *
	 * @var Settings
	 */
	private Settings $settings;

	/**
	 * Constructor.
	 *
	 * @param Settings $settings Plugin settings.
	 */
	public function __construct( Settings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Register hooks if the optimization is enabled.
	 */
	public function boot(): void {
		if ( ! $this->settings->get( 'speed.optimize_heartbeat', true ) ) {
			return;
		}

		// Disable heartbeat on frontend (not needed there).
		add_action( 'init', array( $this, 'control_heartbeat' ), 1 );

		// Slow down heartbeat in admin (except post editor where it's needed for autosave).
		add_filter( 'heartbeat_settings', array( $this, 'adjust_heartbeat_interval' ) );
	}

	/**
	 * Deregister heartbeat on frontend pages where it's not needed.
	 */
	public function control_heartbeat(): void {
		if ( is_admin() ) {
			return;
		}

		wp_deregister_script( 'heartbeat' );
	}

	/**
	 * Increase heartbeat interval on non-editor admin pages.
	 *
	 * The post editor needs frequent heartbeat for autosave (default 15s).
	 * Other admin pages can use a longer interval (60s).
	 *
	 * @param array<string, mixed> $settings Heartbeat settings.
	 * @return array<string, mixed> Modified settings.
	 */
	public function adjust_heartbeat_interval( array $settings ): array {
		global $pagenow;

		// Keep default interval on post editor pages (autosave needs it).
		if ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) {
			return $settings;
		}

		// Slow heartbeat to 60 seconds on all other admin pages.
		$settings['interval'] = 60;

		return $settings;
	}
}
