<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
/**
 * Jetpack Heartbeat.
 *
 * @package automattic/jetpack
 */

use Automattic\Jetpack\Heartbeat;

/**
 * Jetpack Heartbeat.
 */
class Jetpack_Heartbeat {

	/**
	 * Holds the singleton instance of this class
	 *
	 * @since 2.3.3
	 * @var Jetpack_Heartbeat
	 */
	private static $instance = false;

	/**
	 * Holds the singleton instance of the proxied class
	 *
	 * @since 8.9.0
	 * @var Automattic\Jetpack\Heartbeat
	 */
	private static $proxied_instance = false;

	/**
	 * Singleton
	 *
	 * @since 2.3.3
	 * @static
	 * @return Jetpack_Heartbeat
	 */
	public static function init() {
		if ( ! self::$instance ) {
			self::$instance         = new Jetpack_Heartbeat();
			self::$proxied_instance = Heartbeat::init();
		}

		return self::$instance;
	}

	/**
	 * Constructor for singleton
	 *
	 * @since 2.3.3
	 */
	private function __construct() {
		add_filter( 'jetpack_heartbeat_stats_array', array( $this, 'add_stats_to_heartbeat' ) );
	}

	/**
	 * Generates Jetpack plugin heartbeat stats data.
	 *
	 * Site environment stats (WordPress/PHP versions, site configuration, etc.) are generated by
	 * the Connection package via `Automattic\Jetpack\Heartbeat::get_environment_stats()` so they are
	 * reported for every connected site. This method only returns Jetpack-plugin-specific stats.
	 *
	 * @param string $prefix Prefix to add before stats identifier.
	 *
	 * @return array The stats array.
	 */
	public static function generate_stats_array( $prefix = '' ) {
		$return = array();

		$return[ "{$prefix}version" ]        = JETPACK__VERSION;
		$return[ "{$prefix}branch" ]         = (float) JETPACK__VERSION;
		$return[ "{$prefix}manage-enabled" ] = true;

		foreach ( Jetpack::get_available_modules() as $slug ) {
			$return[ "{$prefix}module-{$slug}" ] = Jetpack::is_module_active( $slug ) ? 'on' : 'off';
		}

		return $return;
	}

	/**
	 * Add Jetpack Stats array to Heartbeat if Jetpack is connected
	 *
	 * @since 8.9.0
	 *
	 * @param array $stats Jetpack Heartbeat stats.
	 * @return array $stats
	 */
	public function add_stats_to_heartbeat( $stats ) {

		if ( ! Jetpack::is_connection_ready() ) {
			return $stats;
		}

		$jetpack_stats = self::generate_stats_array();

		return array_merge( $stats, $jetpack_stats );
	}
}
