<?php
/**
 * Dependencies class.
 *
 * @package DokanKits\Admin
 * @since   3.0.0
 */

namespace DokanKits\Admin\Notices;

/**
 * Dependencies Class
 *
 * Handles plugin dependency checking and management
 *
 * @since 3.0.0
 * @package DokanKits\Admin
 */
class Dependencies {

	/**
	 * Show missing dependencies notice (static method for early plugin loading)
	 *
	 * This method is called before the plugin container is initialized,
	 * when WooCommerce or Dokan classes are not available.
	 *
	 * @since 3.0.0
	 * @return void
	 */
	public static function missing_dependencies_notice(): void {
		$missing_plugins = array();

		// Check for WooCommerce.
		if ( ! is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
			$missing_plugins[] = array(
				'name' => 'WooCommerce',
				'slug' => 'woocommerce',
				'file' => 'woocommerce/woocommerce.php',
			);
		}

		// Check for Dokan.
		if ( ! is_plugin_active( 'dokan-lite/dokan.php' ) ) {
			$missing_plugins[] = array(
				'name' => 'Dokan Lite',
				'slug' => 'dokan-lite',
				'file' => 'dokan-lite/dokan.php',
			);
		}

		if ( empty( $missing_plugins ) ) {
			return;
		}

		$plugin_list   = array();
		$install_links = array();

		foreach ( $missing_plugins as $plugin ) {
			$plugin_list[] = '<strong>' . esc_html( $plugin['name'] ) . '</strong>';

			// Check if plugin is installed but not active.
			if ( self::is_plugin_file_installed( $plugin['file'] ) ) {
				$install_links[] = sprintf(
					'<a href="%s" class="button button-primary">%s</a>',
					wp_nonce_url( admin_url( 'plugins.php?action=activate&plugin=' . $plugin['file'] ), 'activate-plugin_' . $plugin['file'] ),
					/* translators: %s: Plugin name */
					sprintf( __( 'Activate %s', 'dokan-kits' ), $plugin['name'] )
				);
			} else {
				$install_links[] = sprintf(
					'<a href="%s" class="button button-secondary">%s</a>',
					admin_url( 'plugin-install.php?s=' . $plugin['slug'] . '&tab=search&type=term' ),
					/* translators: %s: Plugin name */
					sprintf( __( 'Install %s', 'dokan-kits' ), $plugin['name'] )
				);
			}
		}

		$message = sprintf(
			/* translators: %s: List of required plugins */
			__( 'Dokan Kits requires the following plugins to be active: %s', 'dokan-kits' ),
			implode( ', ', $plugin_list )
		);

		$message .= '<p>' . implode( ' ', $install_links ) . '</p>';

		printf(
			'<div class="notice notice-error is-dismissible"><p>%s</p></div>',
			wp_kses_post( $message )
		);
	}

	/**
	 * Check if a plugin file is installed (static helper method)
	 *
	 * @since 3.0.0
	 * @param string $plugin_file Plugin file path.
	 * @return bool
	 */
	private static function is_plugin_file_installed( string $plugin_file ): bool {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php'; // @phpstan-ignore-line
		}

		$installed_plugins = get_plugins();
		return isset( $installed_plugins[ $plugin_file ] );
	}
}
