<?php

namespace EasyCriticalCSS;

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

class Compatibility_WP_Rocket extends Compatibility {
	public static function init() {
		self::add_admin_notice_hook( [ __CLASS__, 'display_admin_notice' ] );
		add_action( 'admin_post_uncheck_wp_rocket_critical_css', [ __CLASS__, 'uncheck_wp_rocket_critical_css' ] );
	}

	public static function is_rocket_installed() {
		return defined( 'WP_ROCKET_VERSION' );
	}

	public static function get_rocket_css_optimization_status() {
		if ( ! self::is_rocket_installed() || ! function_exists( 'get_rocket_option' ) ) {
			return 'disabled';
		}

		$method = get_rocket_option( 'css_delivery_method' );

		if ( $method === 'async' ) {
			return 'optimize_css_delivery';
		}

		if ( $method === 'remove_unused_css' ) {
			return 'remove_unused_css';
		}

		// Fallback for older versions of WP Rocket.
		if ( get_rocket_option( 'optimize_css_delivery' ) ) {
			return 'optimize_css_delivery';
		}

		if ( get_rocket_option( 'remove_unused_css' ) ) {
			return 'remove_unused_css';
		}

		return 'disabled';
	}

	public static function is_rocket_critical_activated() {
		// Allow override for testing or advanced use
		$override = apply_filters( 'easy_cc_mock_rocket_critical_active', null );
		if ( null !== $override ) {
			return (bool) $override;
		}

		return self::get_rocket_css_optimization_status() !== 'disabled';
	}

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

		$admin_url = wp_nonce_url(
			admin_url( 'admin-post.php?action=uncheck_wp_rocket_critical_css' ),
			'uncheck_wp_rocket_critical_css_action'
		);

		self::render_admin_notice(
			esc_html__( "WP Rocket's Optimize CSS Delivery is currently active. Easy Critical CSS has been paused to avoid conflicts.", 'easy-critical-css' ),
			__( 'Uncheck WP Rocket Optimize CSS Delivery', 'easy-critical-css' ),
			$admin_url
		);
	}

	public static function uncheck_wp_rocket_critical_css() {
		// Verify permissions.
		if ( ! current_user_can( 'manage_options' ) || check_admin_referer( 'uncheck_wp_rocket_critical_css_action' ) ) {
			wp_die( esc_html( __( 'You do not have permission to perform this action.', 'easy-critical-css' ) ) );
		}

		// Ensure WP Rocket is installed with the function we need before proceeding.
		if ( ! self::is_rocket_installed() || ! function_exists( 'update_rocket_option' ) ) {
			wp_die( esc_html( __( 'WP Rocket is not installed.', 'easy-critical-css' ) ) );
		}

		// Disable WP Rocket's Critical CSS settings.
		update_rocket_option( 'optimize_css_delivery', 0 );
		update_rocket_option( 'remove_unused_css', 0 );
		update_rocket_option( 'css_delivery_method', '' );

		wp_safe_redirect( admin_url( 'index.php' ) );
		exit;
	}
}
