<?php
/**
 * Registers the legacy license-based stable updater when Divi 5 is active.
 *
 * Divi 4 loads {@see Woo_DS_run_updater()} via includes; Divi 5 does not, so stable updates
 * would rely only on Update URI. This mirrors the Divi 4 path when "Allow Beta Updates" is off.
 *
 * @package dsm-supreme-modules-pro-for-divi
 */

declare( strict_types=1 );

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

if ( function_exists( 'dsm_is_marketplace_build' ) && dsm_is_marketplace_build() ) {
	return;
}

/**
 * Load licence + updater classes (deferred auto-hook so we can call {@see Woo_DS_run_updater()} on plugins_loaded).
 *
 * @return void
 */
function dsm_stable_plugin_updater_load_classes(): void {
	if ( ! defined( 'DSM_DIR_PATH' ) ) {
		return;
	}

	if ( ! class_exists( 'DSM_PRO_licence', false ) ) {
		require_once DSM_DIR_PATH . 'divi-4/includes/license/class.sl.licence.php';
	}

	if ( class_exists( 'Woo_DS_PluginUpdate', false ) ) {
		return;
	}

	if ( ! defined( 'DSM_DEFER_STABLE_PLUGIN_UPDATER' ) ) {
		define( 'DSM_DEFER_STABLE_PLUGIN_UPDATER', true );
	}

	require_once DSM_DIR_PATH . 'divi-4/includes/license/class.sl.plugin-updater.php';
}

/**
 * Attach stable update filters when not on the beta opt-in channel (Divi 5 and any path without the D4 bootstrap).
 *
 * @return void
 */
function dsm_register_stable_license_plugin_updater(): void {
	if ( ! function_exists( 'dsm_beta_updates_opt_in_is_enabled' ) ) {
		return;
	}

	if ( dsm_beta_updates_opt_in_is_enabled() ) {
		return;
	}

	if ( class_exists( 'Woo_DS_PluginUpdate', false ) ) {
		return;
	}

	dsm_stable_plugin_updater_load_classes();

	if ( ! function_exists( 'Woo_DS_run_updater' ) ) {
		return;
	}

	static $attached = false;

	if ( $attached ) {
		return;
	}

	Woo_DS_run_updater();
	$attached = true;
}

add_action( 'plugins_loaded', 'dsm_register_stable_license_plugin_updater', 18 );
