<?php

namespace EasyCriticalCSS;

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

class Compatibility_Trellis extends Compatibility {
	public static function init() {
		self::add_admin_notice_hook( [ __CLASS__, 'display_admin_notice' ] );
		add_action( 'admin_post_uncheck_trellis_critical_css', [ __CLASS__, 'uncheck_trellis_critical_css' ] );
	}

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

		// Is Trellis installed?
		if ( ! class_exists( 'Mediavine\Trellis\Init' ) || ! method_exists( 'Mediavine\Trellis\Settings', 'read_value' ) ) {
			return false;
		}

		return \Mediavine\Trellis\Settings::read_value( 'enable_critical_css', false );
	}

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

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

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

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

		// Ensure Trellis is installed before proceeding.
		if (
			! class_exists( 'Mediavine\Trellis\Init' )
			|| ! method_exists( 'Mediavine\Trellis\Settings', 'read' )
			|| ! method_exists( 'Mediavine\Trellis\Settings', 'upsert' )
		) {
			wp_die( esc_html( __( 'Trellis is not installed.', 'easy-critical-css' ) ) );
		}

		// Prep Trellis setting.
		$enable_critical_css          = \Mediavine\Trellis\Settings::read( 'enable_critical_css', null, true );
		$enable_critical_css['value'] = false;

		// Uncheck Trellis' Critical CSS setting.
		\Mediavine\Trellis\Settings::upsert( $enable_critical_css, false );

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