<?php
/**
 * BaseCloud Boost — Plugin Compatibility
 *
 * @package BaseCloud\Boost\Compatibility
 */

declare( strict_types=1 );

namespace BaseCloud\Boost\Compatibility;

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

use BaseCloud\Boost\Core\Cache_Purge;

/**
 * Provides compatibility with popular WordPress plugins.
 */
class Plugin_Compat {

	/** @var string[] Known conflicting caching plugins. */
	private const CONFLICTING_PLUGINS = [
		'w3-total-cache/w3-total-cache.php',
		'wp-super-cache/wp-cache.php',
		'wp-rocket/wp-rocket.php',
		'litespeed-cache/litespeed-cache.php',
		'sg-cachepress/sg-cachepress.php',
		'hummingbird-performance/wp-hummingbird.php',
		'cache-enabler/cache-enabler.php',
		'comet-cache/comet-cache.php',
	];

	/**
	 * Boot all compatibility layers.
	 *
	 * @return void
	 */
	public function boot(): void {
		// Divi: booted unconditionally — Divi is a theme, so its constants are
		// not defined yet at plugins_loaded. Divi_Compat defers its own
		// detection to after_setup_theme and no-ops when Divi is absent.
		( new Divi_Compat() )->boot();

		if ( defined( 'ELEMENTOR_VERSION' ) ) {
			$this->init_elementor_compat();
		}

		if ( defined( 'WPSEO_VERSION' ) ) {
			$this->init_yoast_compat();
		}

		if ( class_exists( 'ACF' ) || function_exists( 'acf_add_local_field_group' ) ) {
			$this->init_acf_compat();
		}
	}

	/**
	 * Detect active conflicting caching plugins.
	 *
	 * @return string[] Human-readable names.
	 */
	public function detect_conflicts(): array {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$conflicts = [];
		foreach ( self::CONFLICTING_PLUGINS as $plugin_file ) {
			if ( is_plugin_active( $plugin_file ) ) {
				$data        = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin_file, false, false );
				$conflicts[] = $data['Name'] ?? $plugin_file;
			}
		}

		return $conflicts;
	}

	/**
	 * Purge cache when Elementor saves a page.
	 *
	 * @return void
	 */
	private function init_elementor_compat(): void {
		add_action( 'elementor/editor/after_save', static function ( int $post_id ): void {
			( new Cache_Purge() )->purge_post( $post_id );
		} );
	}

	/**
	 * Purge cache when Yoast SEO settings are saved.
	 *
	 * @return void
	 */
	private function init_yoast_compat(): void {
		add_action( 'wpseo_save_options', static function (): void {
			( new Cache_Purge() )->purge_all();
		} );
	}

	/**
	 * Purge post cache when ACF fields are saved.
	 *
	 * @return void
	 */
	private function init_acf_compat(): void {
		add_action( 'acf/save_post', static function ( $post_id ): void {
			if ( is_numeric( $post_id ) && (int) $post_id > 0 ) {
				( new Cache_Purge() )->purge_post( (int) $post_id );
			}
		}, 20 );
	}
}
