<?php
/**
 * WooCommerce soft-dependency detector + admin notice.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Compat;

defined( 'ABSPATH' ) || exit;

final class WooCommerce_Check {

	public static function register(): void {
		add_action( 'admin_notices', array( __CLASS__, 'maybe_global_notice' ) );
	}

	public static function is_active(): bool {
		return class_exists( '\\WooCommerce' );
	}

	public static function shop_url(): string {
		if ( self::is_active() && function_exists( 'wc_get_page_permalink' ) ) {
			$url = wc_get_page_permalink( 'shop' );
			if ( is_string( $url ) && $url ) {
				return $url;
			}
		}
		return home_url( '/' );
	}

	public static function checkout_url(): string {
		if ( self::is_active() && function_exists( 'wc_get_checkout_url' ) ) {
			return wc_get_checkout_url();
		}
		return home_url( '/' );
	}

	public static function render_notice(): void {
		?>
		<div class="wmk-notice wmk-notice-warning" role="alert">
			<div class="wmk-notice-icon" aria-hidden="true">!</div>
			<div class="wmk-notice-body">
				<strong><?php esc_html_e( 'WooCommerce is required', 'suitemkt3k' ); ?></strong>
				<p><?php esc_html_e( 'This section needs WooCommerce active in order to work. Please install and activate it.', 'suitemkt3k' ); ?></p>
			</div>
			<div class="wmk-notice-actions">
				<a class="wmk-btn wmk-btn-primary" href="<?php echo esc_url( self::install_url() ); ?>">
					<?php esc_html_e( 'Install / Activate WooCommerce', 'suitemkt3k' ); ?>
				</a>
			</div>
		</div>
		<?php
	}

	public static function maybe_global_notice(): void {
		if ( self::is_active() ) {
			return;
		}
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || strpos( (string) $screen->id, 'suitemkt3k' ) === false ) {
			return;
		}
	}

	private static function install_url(): string {
		if ( file_exists( WP_PLUGIN_DIR . '/woocommerce/woocommerce.php' ) ) {
			return wp_nonce_url(
				self_admin_url( 'plugins.php?action=activate&plugin=woocommerce/woocommerce.php' ),
				'activate-plugin_woocommerce/woocommerce.php'
			);
		}
		return wp_nonce_url(
			self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ),
			'install-plugin_woocommerce'
		);
	}
}
