<?php
defined( 'ABSPATH' ) || exit;

/**
 * WooCommerce dependency checks and compatibility declarations.
 */
class Formulate_Pricing_Dependencies {

	const WC_PLUGIN_FILE = 'woocommerce/woocommerce.php';

	/**
	 * Whether WooCommerce is installed and active.
	 *
	 * @return bool
	 */
	public static function is_woocommerce_active() {
		if ( class_exists( 'WooCommerce' ) ) {
			return true;
		}

		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		return is_plugin_active( self::WC_PLUGIN_FILE );
	}

	/**
	 * Run on activation: block activation when WooCommerce is missing.
	 */
	public static function on_activation() {
		if ( self::is_woocommerce_active() ) {
			return;
		}

		if ( ! function_exists( 'deactivate_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		deactivate_plugins( plugin_basename( FORMULATE_PRICING_FILE ) );

		wp_die(
			wp_kses_post(
				sprintf(
					/* translators: %s: WooCommerce plugin name */
					__( '<strong>Formulate Pricing</strong> requires %s to be installed and active.', 'formulate-pricing' ),
					'<a href="https://wordpress.org/plugins/woocommerce/">WooCommerce</a>'
				)
			),
			esc_html__( 'Plugin Activation Error', 'formulate-pricing' ),
			array( 'back_link' => true )
		);
	}

	/**
	 * Admin notice when WooCommerce is not active.
	 */
	public static function admin_notice_missing_woocommerce() {
		if ( self::is_woocommerce_active() ) {
			return;
		}

		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}

		printf(
			'<div class="notice notice-error"><p><strong>%1$s</strong> %2$s</p></div>',
			esc_html__( 'Formulate Pricing', 'formulate-pricing' ),
			esc_html__( 'requires WooCommerce to be installed and active. Please install and activate WooCommerce.', 'formulate-pricing' )
		);
	}

	/**
	 * Declare compatibility with WooCommerce features (HPOS, etc.).
	 */
	public static function declare_woocommerce_compatibility() {
		if ( ! class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
			return;
		}

		\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
			'custom_order_tables',
			FORMULATE_PRICING_FILE,
			true
		);
	}
}

add_action( 'before_woocommerce_init', array( 'Formulate_Pricing_Dependencies', 'declare_woocommerce_compatibility' ) );
