<?php
/**
 * Known page-cache plugin detection.
 *
 * Shared by the SEO analyzer and the admin cache-compatibility notice.
 *
 * @package SEOvaultSEO\Utils
 */

namespace SEOvaultSEO\Utils;

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

/**
 * Detects common WordPress page-cache plugins.
 */
final class CachePlugins {

	/**
	 * Known cache plugin bootstrap files mapped to display names.
	 *
	 * @return array<string, string> plugin_file => label
	 */
	public static function get_known_plugins() {
		$plugins = array(
			'wp-rocket/wp-rocket.php'             => 'WP Rocket',
			'w3-total-cache/w3-total-cache.php'   => 'W3 Total Cache',
			'wp-super-cache/wp-cache.php'         => 'WP Super Cache',
			'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
			'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
			'cache-enabler/cache-enabler.php'     => 'Cache Enabler',
			'sg-cachepress/sg-cachepress.php'     => 'SiteGround Optimizer',
			'wpr-cache/wpr-cache.php'             => 'WP Rocket Cache',
			'breeze/breeze.php'                   => 'Breeze',
			'comet-cache/comet-cache.php'         => 'Comet Cache',
		);

		/**
		 * Filter the known cache plugin map used for detection.
		 *
		 * @param array<string, string> $plugins plugin_file => label.
		 */
		return apply_filters( 'seovaultseo_known_cache_plugins', $plugins );
	}

	/**
	 * Active plugin basenames for the current site (and network when multisite).
	 *
	 * @return array<int, string>
	 */
	public static function get_active_plugin_files() {
		$active = get_option( 'active_plugins', array() );
		if ( ! is_array( $active ) ) {
			$active = array();
		}

		if ( is_multisite() ) {
			$network = get_site_option( 'active_sitewide_plugins', array() );
			if ( is_array( $network ) ) {
				$active = array_unique( array_merge( $active, array_keys( $network ) ) );
			}
		}

		return $active;
	}

	/**
	 * Active known cache plugins as display names.
	 *
	 * @return array<int, string>
	 */
	public static function get_active() {
		$active_files = self::get_active_plugin_files();
		$found        = array();

		foreach ( self::get_known_plugins() as $file => $label ) {
			if ( in_array( $file, $active_files, true ) ) {
				$found[] = $label;
			}
		}

		return array_values( array_unique( $found ) );
	}

	/**
	 * Whether any known cache plugin is active.
	 *
	 * @return bool
	 */
	public static function is_active() {
		return ! empty( self::get_active() );
	}
}
