<?php
/**
 * BaseCloud Boost — Heartbeat Control
 *
 * @package BaseCloud\Boost\Core
 */

declare( strict_types=1 );

namespace BaseCloud\Boost\Core;

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

/**
 * Controls WordPress Heartbeat API to reduce server load.
 */
class Heartbeat_Control {

	/**
	 * Boot heartbeat control.
	 *
	 * @return void
	 */
	public function boot(): void {
		if ( ! BCBOOST_get_option( 'heartbeat_control', true ) ) {
			return;
		}

		add_filter( 'heartbeat_settings',    [ $this, 'modify_heartbeat_settings' ] );
		add_filter( 'heartbeat_send',        [ $this, 'modify_heartbeat_response' ], 10, 2 );
	}

	/**
	 * Modify heartbeat frequency settings.
	 *
	 * @param array $settings Current heartbeat settings.
	 * @return array Modified settings.
	 */
	public function modify_heartbeat_settings( array $settings ): array {
		$interval = (int) BCBOOST_get_option( 'heartbeat_interval', 60 );
		$settings['interval'] = max( 15, $interval );
		return $settings;
	}

	/**
	 * Optionally reduce heartbeat payload.
	 *
	 * @param mixed $response Heartbeat response (string or array depending on WP context).
	 * @param mixed $data     Heartbeat request data.
	 * @return mixed
	 */
	public function modify_heartbeat_response( $response, $data ) {
		return $response;
	}
}
