<?php

defined('ABSPATH') || exit;

class NXTPDFPreflightChecker {
	/**
	 * Check if the required PHP version is met.
	 *
	 * @return bool True if the requirement is met, false otherwise.
	 */
	public static function checkPHPVersion(): bool {
		return version_compare(PHP_VERSION, '7.4', '>=');
	}

	/**
	 * Check if the required plugin type is active.
	 *
	 * @param string $pro_basename
	 * @return bool
	 */
	public static function isProActive(string $pro_basename): bool {
		// This constant need to be defined in the Pro version's main file, so if it's defined and true, we can assume the Pro version is active.
		if (defined('NXTPDF_PREFLIGHT_CHECKER') && NXTPDF_PREFLIGHT_CHECKER) {
			return true;
		}

		$active_plugins = (array) get_option('active_plugins', []);

		if (in_array($pro_basename, $active_plugins, true)) {
			return ! self::isPluginPaused($pro_basename);
		}

		if (! is_multisite()) {
			return false;
		}

		$network_active_plugins = array_keys((array) get_site_option('active_sitewide_plugins', []));

		if (in_array($pro_basename, $network_active_plugins, true)) {
			return ! self::isPluginPaused($pro_basename);
		}

		return false;
	}

	/**
	 * Check if a plugin is paused by WordPress Recovery Mode.
	 *
	 * @param string $pro_basename
	 * @return bool
	 */
	private static function isPluginPaused(string $pro_basename): bool {
		if (! function_exists('wp_paused_plugins')) {
			return false;
		}

		$plugin_dir = dirname($pro_basename);

		return (bool) wp_paused_plugins()->get($plugin_dir);
	}

	/**
	 * Add the dormant notice in the plugin page if the Pro version is active.
	 * This method should be hooked to 'admin_notices' and 'network_admin_notices' actions.
	 * currently, it is not added to avoid confusion for users who have both free and pro versions active, but it can be enabled in the future if needed.
	 *
	 * @return void
	 */
	public static function renderDormantNotice(): void {
		if (! current_user_can('activate_plugins')) {
			return;
		}

		$screen = function_exists('get_current_screen') ? get_current_screen() : null;

		if ($screen && ! in_array($screen->id, ['plugins', 'plugins-network'], true)) {
			return;
		}

		printf(
			'<div class="notice notice-info"><p>%s</p></div>',
			esc_html('Free Plugin is active but dormant because the Pro version of the same Plugin is also active. Only the Pro plugin will run.')
		);
	}

}
