<?php
/**
 * Blocks deactivation of the free plugin while the Pro add-on is active.
 *
 * Pro depends on the free plugin (ADR-09). On WordPress 6.5+ this is enforced
 * natively by core's plugin-dependency API via Pro's `Requires Plugins:
 * trx-auto-dealer` header — core disables the free plugin's "Deactivate" link
 * and explains why. WordPress 6.4 (our minimum) predates that API, so this
 * guard provides the same protection: when Pro is active it removes the free
 * plugin's Deactivate link and replaces it with an inert label, preventing the
 * broken half-state (Pro left "active" but non-functional) testers reported
 * when deactivating free first.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.3
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Free-side fallback for core's WP 6.5 plugin-dependency enforcement.
 */
class ProDependencyGuard {

	private const FREE_BASENAME = 'trx-auto-dealer/trx-auto-dealer.php';
	private const PRO_BASENAME  = 'trx-auto-dealer-pro/trx-auto-dealer-pro.php';

	/**
	 * Register hooks. No-ops on WP 6.5+ where core's WP_Plugin_Dependencies
	 * already disables the free Deactivate link from Pro's `Requires Plugins`
	 * header — applying our own filter too would double up the messaging.
	 *
	 * @return void
	 */
	public function register(): void {
		if ( class_exists( '\WP_Plugin_Dependencies' ) ) {
			return;
		}

		add_filter( 'plugin_action_links_' . self::FREE_BASENAME, array( $this, 'lockDeactivateLink' ) );
		add_filter( 'network_admin_plugin_action_links_' . self::FREE_BASENAME, array( $this, 'lockDeactivateLink' ) );
	}

	/**
	 * Replace the free plugin's "Deactivate" action link with an inert label
	 * while Pro is active.
	 *
	 * @param array<string, string> $links Plugin action links keyed by action.
	 * @return array<string, string>
	 */
	public function lockDeactivateLink( array $links ): array {
		if ( ! self::isProActive() ) {
			return $links;
		}

		if ( isset( $links['deactivate'] ) ) {
			$links['deactivate'] = sprintf(
				'<span class="trx-ad-dep-locked" style="color:#a7aaad;" title="%s">%s</span>',
				esc_attr__( 'Deactivate ThemeREX Auto Dealer Pro first.', 'trx-auto-dealer' ),
				esc_html__( 'Required by Pro', 'trx-auto-dealer' )
			);
		}

		return $links;
	}

	/**
	 * Is the Pro add-on active? Loose, class-free string check so the free
	 * plugin never hard-depends on Pro's code being loaded.
	 *
	 * @return bool
	 */
	private static function isProActive(): bool {
		$active = (array) get_option( 'active_plugins', array() );
		if ( in_array( self::PRO_BASENAME, $active, true ) ) {
			return true;
		}

		if ( is_multisite() ) {
			$network = (array) get_site_option( 'active_sitewide_plugins', array() );
			if ( isset( $network[ self::PRO_BASENAME ] ) ) {
				return true;
			}
		}

		return false;
	}
}
