<?php
/**
 * Plugin Name: WPPowerSuite Pro
 * Plugin URI: https://wppowersuite.com/
 * Description: Premium modules and licensing for WPPowerSuite Lite. Requires the free WPPowerSuite Lite plugin.
 * Version: 1.1.0
 * Author: Muhammad Muzammil
 * Author URI: https://wppowersuite.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: wppowersuite-lite
 * Domain Path: /languages
 * Requires at least: 6.8
 * Requires PHP: 8.1
 * Requires Plugins: wppowersuite-lite
 * Update URI: https://wppowersuite.com
 * Network: true
 *
 * Secure design (rafter-secure-design / auth + deployment):
 * - Identity: WordPress site admin. License is the existing Elite Licenser
 *   site entitlement — no new auth primitive.
 * - AuthZ: Pro module PHP lives only in this add-on. Lite never ships it.
 *   Missing licensing on Lite is deny (not entitle).
 * - Updates: commercial updater targets this file, never the wordpress.org
 *   Lite plugin (guideline 8 / remote install of premium over .org).
 * - Activation without Lite: admin notice, no module load.
 * - Lite older than Pro: admin notice to install the matching free
 *   build from the client portal until wordpress.org reviews it.
 *
 * @package WP_PowerSuite_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'WP_POWERSUITE_PRO_VERSION', '1.1.0' );
define( 'WP_POWERSUITE_PRO_ACTIVE', true );
define( 'WP_POWERSUITE_PRO_FILE', __FILE__ );
define( 'WP_POWERSUITE_PRO_DIR', plugin_dir_path( __FILE__ ) );
define( 'WP_POWERSUITE_PRO_MODULES_DIR', WP_POWERSUITE_PRO_DIR . 'modules' . DIRECTORY_SEPARATOR );
define( 'WP_POWERSUITE_PRO_LICENSING_DIR', WP_POWERSUITE_PRO_DIR . 'includes' . DIRECTORY_SEPARATOR . 'licensing' . DIRECTORY_SEPARATOR );
define( 'WP_POWERSUITE_PRO_FREEMIUM_DIR', WP_POWERSUITE_PRO_DIR . 'freemium' . DIRECTORY_SEPARATOR );
if ( ! defined( 'WP_POWERSUITE_CLIENT_PORTAL_URL' ) ) {
	define( 'WP_POWERSUITE_CLIENT_PORTAL_URL', 'https://wppowersuite.com/clientarea' );
}

/**
 * Whether the free WP PowerSuite plugin is loaded.
 */
function wp_powersuite_pro_lite_is_loaded(): bool {
	return defined( 'WP_POWERSUITE_VERSION' ) && function_exists( 'wp_powersuite_init' );
}

/**
 * Register the Pro modules directory with Lite's registry.
 *
 * @param list<string> $dirs Scan roots.
 * @return list<string>
 */
function wp_powersuite_pro_register_module_dir( array $dirs ): array {
	$dirs[] = WP_POWERSUITE_PRO_MODULES_DIR;
	return $dirs;
}

/**
 * Register the freemium overlay (premium files stripped from Lite).
 *
 * @param list<string> $roots Overlay roots.
 * @return list<string>
 */
function wp_powersuite_pro_register_freemium_dir( array $roots ): array {
	$roots[] = WP_POWERSUITE_PRO_FREEMIUM_DIR;
	return $roots;
}

/**
 * Clear Lite's module cache so Pro modules appear after activate/deactivate.
 */
function wp_powersuite_pro_invalidate_module_cache(): void {
	if ( class_exists( '\WP_PowerSuite\Core\DataRegistry' ) ) {
		\WP_PowerSuite\Core\DataRegistry::clearCaches();
	}
}

/**
 * Register AI classes from this add-on when Lite no longer ships src/AI.
 */
function wp_powersuite_pro_register_ai_autoloader(): void {
	if ( ! function_exists( '\WP_PowerSuite\Bootstrap\register_autoloader' ) ) {
		return;
	}

	$lite_ai = '';
	if ( defined( 'WP_POWERSUITE_SRC_DIR' ) && is_string( WP_POWERSUITE_SRC_DIR ) ) {
		$lite_ai = rtrim( WP_POWERSUITE_SRC_DIR, '/\\' ) . DIRECTORY_SEPARATOR . 'AI' . DIRECTORY_SEPARATOR . 'ConnectionSettings.php';
	}

	if ( $lite_ai !== '' && is_readable( $lite_ai ) ) {
		return;
	}

	$ai_dir = WP_POWERSUITE_PRO_DIR . 'includes' . DIRECTORY_SEPARATOR . 'ai';
	if ( ! is_dir( $ai_dir ) ) {
		return;
	}

	\WP_PowerSuite\Bootstrap\register_autoloader( 'WP_PowerSuite\\AI', $ai_dir );
}

/**
 * Notice when Lite is missing.
 */
function wp_powersuite_pro_missing_lite_notice(): void {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	echo '<div class="notice notice-error"><p>';
	echo esc_html__( 'WPPowerSuite Pro requires the free WPPowerSuite Lite plugin. Install and activate it from wordpress.org, then activate Pro again.', 'wppowersuite-lite' );
	echo '</p></div>';
}

/**
 * Client portal URL for downloading matching Lite builds.
 */
function wp_powersuite_pro_client_portal_url(): string {
	$url = defined( 'WP_POWERSUITE_CLIENT_PORTAL_URL' )
		? (string) WP_POWERSUITE_CLIENT_PORTAL_URL
		: 'https://wppowersuite.com/clientarea';

	return esc_url_raw( (string) apply_filters( 'wp_powersuite_client_portal_url', $url ) );
}

/**
 * Whether the free plugin is older than this Pro add-on.
 *
 * Typical during wordpress.org review: Pro is already on the new version
 * and Lite must be installed from the client portal until .org is live.
 *
 * @param string $lite_version Installed Lite version. Empty uses WP_POWERSUITE_VERSION.
 * @param string $pro_version  Installed Pro version. Empty uses WP_POWERSUITE_PRO_VERSION.
 */
function wp_powersuite_pro_lite_needs_matching_update( string $lite_version = '', string $pro_version = '' ): bool {
	if ( $lite_version === '' && defined( 'WP_POWERSUITE_VERSION' ) ) {
		$lite_version = (string) WP_POWERSUITE_VERSION;
	}
	if ( $pro_version === '' && defined( 'WP_POWERSUITE_PRO_VERSION' ) ) {
		$pro_version = (string) WP_POWERSUITE_PRO_VERSION;
	}

	$lite_version = trim( $lite_version );
	$pro_version  = trim( $pro_version );

	if ( $lite_version === '' || $pro_version === '' ) {
		return false;
	}

	return version_compare( $lite_version, $pro_version, '<' );
}

/**
 * Render the Lite/Pro version-mismatch admin notice.
 *
 * @param string $lite_version Installed Lite version.
 * @param string $pro_version  Installed Pro version.
 */
function wp_powersuite_pro_render_version_mismatch_notice( string $lite_version, string $pro_version ): void {
	$portal_url = wp_powersuite_pro_client_portal_url();
	$hide_link  = class_exists( '\WP_PowerSuite\Core\WhiteLabel', false )
		&& \WP_PowerSuite\Core\WhiteLabel::shouldHideExternalLinks();

	echo '<div class="notice notice-warning" data-wpps-plugin="true"><p>';
	printf(
		/* translators: 1: Pro version, 2: Lite version */
		esc_html__( 'WPPowerSuite Pro %1$s does not match the free WPPowerSuite plugin (%2$s). Update the free plugin to %1$s by downloading it from the client portal until that version is approved and live on WordPress.org.', 'wppowersuite-lite' ),
		esc_html( $pro_version ),
		esc_html( $lite_version )
	);
	if ( $portal_url !== '' && ! $hide_link ) {
		echo ' <a href="' . esc_url( $portal_url ) . '" target="_blank" rel="noopener noreferrer">';
		esc_html_e( 'Open the client portal', 'wppowersuite-lite' );
		echo '</a>';
	}
	echo '</p></div>';
}

/**
 * Notice when Lite is behind Pro (wordpress.org review lag).
 */
function wp_powersuite_pro_version_mismatch_notice(): void {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	if ( ! wp_powersuite_pro_lite_needs_matching_update() ) {
		return;
	}

	wp_powersuite_pro_render_version_mismatch_notice(
		defined( 'WP_POWERSUITE_VERSION' ) ? (string) WP_POWERSUITE_VERSION : '',
		defined( 'WP_POWERSUITE_PRO_VERSION' ) ? (string) WP_POWERSUITE_PRO_VERSION : ''
	);
}

add_action(
	'plugins_loaded',
	static function (): void {
		if ( ! wp_powersuite_pro_lite_is_loaded() ) {
			add_action( 'admin_notices', 'wp_powersuite_pro_missing_lite_notice' );
			add_action( 'network_admin_notices', 'wp_powersuite_pro_missing_lite_notice' );
			return;
		}

		add_action( 'admin_notices', 'wp_powersuite_pro_version_mismatch_notice' );
		add_action( 'network_admin_notices', 'wp_powersuite_pro_version_mismatch_notice' );

		add_filter( 'wp_powersuite_module_scan_directories', 'wp_powersuite_pro_register_module_dir' );
		add_filter( 'wp_powersuite_freemium_file_roots', 'wp_powersuite_pro_register_freemium_dir' );

		$pro_settings_ui_candidates = [];
		if ( defined( 'WP_POWERSUITE_SRC_DIR' ) && is_string( WP_POWERSUITE_SRC_DIR ) ) {
			$pro_settings_ui_candidates[] = rtrim( WP_POWERSUITE_SRC_DIR, '/\\' ) . DIRECTORY_SEPARATOR . 'Admin' . DIRECTORY_SEPARATOR . 'ProSettingsUi.php';
		}
		$pro_settings_ui_candidates[] = WP_POWERSUITE_PRO_DIR . 'includes' . DIRECTORY_SEPARATOR . 'pro-settings-ui.php';
		foreach ( $pro_settings_ui_candidates as $pro_settings_ui ) {
			if ( is_readable( $pro_settings_ui ) ) {
				require_once $pro_settings_ui;
				break;
			}
		}
	},
	1
);

// AI classes must register after Lite's autoloader (plugins_loaded:5). Priority 1 is too early.
add_action( 'wp_powersuite_autoloader_ready', 'wp_powersuite_pro_register_ai_autoloader' );
add_action( 'plugins_loaded', 'wp_powersuite_pro_register_ai_autoloader', 6 );

register_activation_hook(
	__FILE__,
	static function (): void {
		if ( ! wp_powersuite_pro_lite_is_loaded() ) {
			return;
		}
		wp_powersuite_pro_invalidate_module_cache();
	}
);

register_deactivation_hook(
	__FILE__,
	static function (): void {
		wp_powersuite_pro_invalidate_module_cache();
	}
);
