<?php
/**
 * CacheLoop – HealthLoop Report Bridge
 *
 * Registers CacheLoop as a data provider on HealthLoop's public
 * `healthloop_data_providers` filter — an open contract any InTouchDesign
 * plugin can join with no hard dependency on HealthLoop being installed
 * (see healthloop/includes/class-hl-data-providers.php for the full
 * contract this implements). When HealthLoop isn't active, add_filter()
 * here simply has nothing to call it — this file is a no-op cost.
 *
 * Real data comes from CACHELOOP_Stats, which tracks hits/misses/purges as
 * append-only daily log files (see class-cl-stats.php for why).
 *
 * @package CacheLoop
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class CACHELOOP_HealthLoop_Bridge
 */
class CACHELOOP_HealthLoop_Bridge {

	/**
	 * Registers the provider on HealthLoop's filter.
	 */
	public function __construct() {
		add_filter( 'healthloop_data_providers', array( $this, 'register_provider' ) );
	}

	/**
	 * Adds CacheLoop to the provider registry.
	 *
	 * @param  array $providers Providers registered so far.
	 * @return array
	 */
	public function register_provider( $providers ) {
		$providers[] = array(
			'id'       => 'cacheloop',
			'label'    => __( 'CacheLoop', 'cacheloop-simple-page-cache-speed-optimization' ),
			'callback' => array( __CLASS__, 'get_summary' ),
		);

		return $providers;
	}

	/**
	 * `healthloop_data_providers` callback. Summarizes cache hits, misses,
	 * and purges recorded by CACHELOOP_Stats for the given period.
	 *
	 * @param  DateTime $since Period start.
	 * @param  DateTime $until Period end.
	 * @return array|null
	 */
	public static function get_summary( DateTime $since, DateTime $until ) {
		if ( ! class_exists( 'CACHELOOP_Stats' ) ) {
			require_once CACHELOOP_PLUGIN_DIR . 'includes/class-cl-stats.php';
		}

		$totals = CACHELOOP_Stats::get_summary( $since, $until );
		$served = $totals['hits'] + $totals['misses'];

		if ( 0 === $served && 0 === $totals['purges'] ) {
			return null;
		}

		$hit_rate      = $served > 0 ? round( ( $totals['hits'] / $served ) * 100, 1 ) : null;
		$summary_parts = array();

		if ( $served > 0 ) {
			$summary_parts[] = sprintf(
				/* translators: 1: number of pages served from cache, 2: hit rate percentage */
				__( '%1$d pages served from cache (%2$s%% hit rate).', 'cacheloop-simple-page-cache-speed-optimization' ),
				$totals['hits'],
				$hit_rate
			);
		}

		if ( $totals['purges'] > 0 ) {
			$summary_parts[] = sprintf(
				/* translators: %d: number of cache purges */
				_n( '%d cache purge.', '%d cache purges.', $totals['purges'], 'cacheloop-simple-page-cache-speed-optimization' ),
				$totals['purges']
			);
		}

		if ( empty( $summary_parts ) ) {
			return null;
		}

		return array(
			'summary' => implode( ' ', $summary_parts ),
			'metrics' => array(
				'hits'     => $totals['hits'],
				'misses'   => $totals['misses'],
				'purges'   => $totals['purges'],
				'hit_rate' => $hit_rate,
			),
		);
	}
}
