<?php

namespace EasyCriticalCSS;

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

class Compatibility_Perfmatters extends Compatibility {
	public static function init() {
		add_filter( 'perfmatters_rest_api_exceptions', [ __CLASS__, 'add_rest_api_exception' ] );
		self::add_admin_notice_hook( [ __CLASS__, 'display_admin_notice' ] );
	}

	public static function add_rest_api_exception( $exceptions ) {
		$exceptions[] = 'easy-critical-css';

		return $exceptions;
	}

	public static function is_perfmatters_installed() {
		return defined( 'PERFMATTERS_VERSION' );
	}

	public static function has_conflicting_css_settings() {
		$override = apply_filters( 'easy_cc_mock_perfmatters_conflict', null );
		if ( null !== $override ) {
			return (bool) $override;
		}

		if ( ! self::is_perfmatters_installed() ) {
			return false;
		}

		$options = get_option( 'perfmatters_options' );
		if ( empty( $options ) || ! is_array( $options ) ) {
			return false;
		}

		$assets            = isset( $options['assets'] ) && is_array( $options['assets'] ) ? $options['assets'] : [];
		$remove_unused_css = ! empty( $assets['remove_unused_css'] );

		// Perfmatters exposes the Clear Used CSS control when Remove Unused CSS is active, so treat either as conflicting.
		if ( ! $remove_unused_css && ! empty( $assets['clear_used_css'] ) ) {
			$remove_unused_css = true;
		}

		$minify_css = ! empty( $assets['minify_css'] );

		return (bool) ( $remove_unused_css || $minify_css );
	}

	public static function display_admin_notice() {
		if ( ! self::has_conflicting_css_settings() ) {
			return;
		}

		$settings_url = is_network_admin()
			? network_admin_url( 'settings.php?page=perfmatters#css' )
			: admin_url( 'options-general.php?page=perfmatters#css' );

		self::render_admin_notice(
			esc_html__( 'Perfmatters Clear Used CSS or Minify CSS is currently active. Easy Critical CSS has been paused to avoid conflicts.', 'easy-critical-css' ),
			__( 'Open Perfmatters CSS Settings', 'easy-critical-css' ),
			$settings_url
		);
	}
}
