<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class WPRocket
 *
 * Plugin Name: WP Rocket
 * Plugin URI: https://wp-rocket.me/
 * Tested versions: 3.15.1
 */
class WPRocket extends AbstractPlugin {
	public function init(): void {
		add_filter( 'rocket_delay_js_exclusions', [ $this, 'excluded_js' ] );
		add_filter( 'rocket_rucss_inline_atts_exclusions', [ $this, 'add_rucss_inline_atts_exclusions' ] );
		add_filter( 'rocket_rucss_inline_content_exclusions', [ $this, 'add_rucss_inline_content_exclusions' ] );

		// Compatability with Lazy Render Content.
		add_filter( 'rocket_lrc_exclusions', [ $this, 'add_lrc_exclusions' ] );
		add_filter( 'fibofilters/request/html/product_placeholder', [ $this, 'add_skip_lrc_to_product_placeholder' ], PHP_INT_MAX - 5 );
	}

	/**
	 * Adding our scripts to the list of excluded from delayed loading
	 *
	 * @param array $excluded Excluded.
	 */
	public function excluded_js( $excluded ): array {
		// Test if exclusion for FiboFilters is enabled in WP Rocket settings.
		$options = get_option( 'wp_rocket_settings', [] );
		if (
			! empty( $options['delay_js_exclusions_selected'] ) &&
			is_array( $options['delay_js_exclusions_selected'] ) &&
			// You can find hash for our plugin on this list:  https://b.rucss.wp-rocket.me/api/delay-js-exclusions/list.
			in_array( '081461cf-dbd0-42f3-9557-10cdc16cf145', $options['delay_js_exclusions_selected'], true )
		) {
			// This one rule includes: "fibofilters-js", "fibofilters-js-extra", "fibofilters-js-after", etc.
			$excluded[] = 'fibofilters-js';
		}

		return $excluded;
	}

	/**
	 * Adding our inline styles (atts) to the list of excluded from remove from content
	 *
	 * @param array $atts_exclusions Excluded.
	 */
	public function add_rucss_inline_atts_exclusions( $atts_exclusions ): array {
		$atts_exclusions [] = 'fibofilters-inline-css';

		return $atts_exclusions;
	}

	/**
	 * Adding our inline styles (content) to the list of excluded from remove from content
	 *
	 * @param array $content_exclusions Excluded.
	 */
	public function add_rucss_inline_content_exclusions( $content_exclusions ): array {
		$content_exclusions [] = '.fibofilters';

		return $content_exclusions;
	}

	/**
	 * Adding our content to the list of excluded from Lazy Load for Rocket.
	 *
	 * @param array $exclusions Excluded.
	 */
	public function add_lrc_exclusions( $exclusions ): array {
		$exclusions[] = 'id="fibofilters-data"'; // This is redundant, and it is unclear whether it is being taken into account.
		$exclusions[] = 'data-skip-wprocket-lrc="1"';

		return $exclusions;
	}

	/**
	 * Add data-skip-wprocket-lrc attribute to <div> tags in product placeholder
	 *
	 * @param string $html Placeholder HTML.
	 */
	public function add_skip_lrc_to_product_placeholder( string $html ): string {
		return str_replace( '<div', '<div data-skip-wprocket-lrc="1"', $html );
	}
}
