<?php
/**
 * Ultimate Member Elementor Essential Functions
 * 
 * This file contains essential functions for the Ultimate Member Elementor plugin.
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Feature Flag: Use the new unified query engine instead of legacy builders
 * Allows a safe migration path for older sites relying on previous logic.
 */
function um_use_new_query_engine() {
    $use_new_engine = get_option( 'um_use_new_query_engine', true );
    return apply_filters( 'um_use_new_query_engine', $use_new_engine );
}

/**
 * Display notice if the PHP version is unsupported.
 */
function user_elementor_um_php_version_notice(): void {
    printf(
        '<div class="notice notice-error"><p>%s</p></div>',
        esc_html__( 'Ultimate Member Widgets requires PHP 8.0+.', 'ultimate-member-widgets-for-elementor' )
    );
}

/**
 * Display notice if Elementor is not active.
 */
function user_elementor_um_dependency_notice(): void {
    printf(
        '<div class="notice notice-error"><p>%s</p></div>',
        esc_html__( 'Ultimate Member Widgets requires Elementor to be active.', 'ultimate-member-widgets-for-elementor' )
    );
}

/**
 * Register Elementor category
 */
function user_elementor_um_category()
{
    // Get the Elementor instance.
    $elementor = \Elementor\Plugin::instance();

    // Add a category for Ultimate Member elements.
    $elementor->elements_manager->add_category(
        'um-addons-elementor',
        [
            'title' => __('UM Member Directories', 'ultimate-member-widgets-for-elementor'),
            'icon'  => 'font',
        ],
        1
    );

    // Add a category for UM Profile Forms.
    $elementor->elements_manager->add_category(
        'um-profile-forms-elementor',
        [
            'title' => __( 'UM Member Pages', 'ultimate-member-widgets-for-elementor' ),
            'icon'  => 'eicon-person',
        ],
        1
    );
}

/**
 * Get user roles
 */
function user_elementor_um_get_user_roles()
{
    $roles = [];
    $wp_roles = wp_roles();
    
    if ($wp_roles) {
        foreach ($wp_roles->get_names() as $role_value => $role_name) {
            $roles[$role_value] = $role_name;
        }
    }
    
    return $roles;
}

/**
 * Get user meta keys
 */
function user_elementor_um_get_user_meta_keys(): array
{
    $cached = get_transient( 'um_ele_meta_keys' );
    if ( $cached !== false && is_array( $cached ) ) {
        return $cached;
    }

    global $wpdb;
    
    // System/internal meta keys to exclude from user-facing displays
    $excluded_meta_keys = [
        'session_tokens',
        'academy_is_user_migrate_completed_topics',
        'bp_xprofile_visibility_levels',
        'wp_capabilities', 
        'wp_user_level',
        'wp_user-settings',
        'wp_user-settings-time',
        'dismissed_wp_pointers',
        'wp_dashboard_quick_press_last_post_id',
        'wp_metaboxorder_nav-menus',
        'wp_nav_menu_recently_edited',
        'wp_media_library_mode',
        'metaboxhidden_page',
        'metaboxhidden_um_form',
        'pmpro_archived_notifications',
        'managenav-menuscolumnshidden',
        'metaboxhidden_nav-menus',
        'closedpostboxes_nav-menus',
        'locale',
        'rich_editing',
        'syntax_highlighting',
        'comment_shortcuts',
        'admin_color',
        'use_ssl',
        'sensei_tours',
        'show_welcome_panel',
        'tutor_last_login',
        'closedpostboxes_page',
        'closedpostboxes_um_form',
        'dismissed_no_secure_connection_notice',
        'dismissed_update_notice',
        'wud_visible_columns',
        'astra-upgrade-pro-wc',
        'elementor_admin_notices',
        'elementor_introduction',
        'gh_read_notices',
        'mailerpress_fullscreen',
        'mailerpress_go_pro_notice',
        'mailerpress_setup_completed',
        'managememberships_page_pmpro-memberslistcolumnshidden',
        'managememberships_page_pmpro-orderscolumnshidden',
        'managememberships_page_pmpro-subscriptionscolumnshidden',
        'managetoplevel_page_wp_streamcolumnshidden',
        'meta-box-order_product',
        'nav_menu_recently_edited',
        'wp_elementor_connect_common_data',
        'wp_elementor_enable_ai',
        'wud_visible_default_fields',
        'wp_woocommerce_product_import_mapping',
        'wp_product_import_error_log',
        'wp_2fa_totp_key',
        'wp_2fa_global_settings_hash',
        'wp_2fa_enforcement_state',
        'wp_2fa_email_token',
        'wp_2fa_2fa_status',
        'wedocs_hide_pro_notice',
        'wcz_feedback_notice_dismiss',
        'um_account_secure_fields',
        'um_member_directory_data',
        'um_new_notifications',
        'uat_dismiss_stamp',
        'synced_gravatar_hashed_id',
        'pw_new_user_approve_has_signed_in',
        'wppb_pms_cross_promo_dismiss_notification',
        'show_admin_bar_front',
        'wp_persisted_preferences'
    ];
    
    $excluded_meta_keys = apply_filters('um_elementor_excluded_meta_keys', $excluded_meta_keys);
    
    $meta_keys = [];
    
    // Get meta keys from wp_usermeta table
    $results = $wpdb->get_results("
        SELECT DISTINCT meta_key 
        FROM {$wpdb->usermeta} 
        WHERE meta_key NOT LIKE '\_%' 
        ORDER BY meta_key ASC
    ");
    
    if ($results) {
        foreach ($results as $result) {
            // Skip excluded meta keys
            if (!in_array($result->meta_key, $excluded_meta_keys, true)) {
                $meta_keys[$result->meta_key] = $result->meta_key;
            }
        }
    }

    set_transient( 'um_ele_meta_keys', $meta_keys, HOUR_IN_SECONDS );
    
    return $meta_keys;
}

/**
 * Invalidate cached usermeta key list (used by editor field pickers).
 */
function user_elementor_um_delete_meta_keys_cache(): void {
    delete_transient( 'um_ele_meta_keys' );
    delete_transient( 'um_ele_meta_keys_combined' );
}

/**
 * Get user meta keys with human-readable labels (Enhanced Version)
 */
function user_elementor_um_get_user_meta_keys_combine()
{
    $cached = get_transient( 'um_ele_meta_keys_combined' );
    if ( $cached !== false && is_array( $cached ) ) {
        return $cached;
    }

    global $wpdb;
    
    $all_fields = [];
    
    // 1. Get wp_users table columns first
    $user_table_columns = $wpdb->get_col("DESCRIBE {$wpdb->users}");
    
    // Standard wp_users fields with friendly names
    $user_field_labels = [
        'ID' => 'User ID',
        'user_login' => 'Username',
        'user_nicename' => 'Nice Name',
        'user_email' => 'Email Address',
        'user_url' => 'Website URL',
        'user_registered' => 'Registration Date',
        'user_status' => 'User Status',
        'display_name' => 'Display Name'
    ];
    
    // Add wp_users fields (excluding sensitive ones)
    $excluded_user_fields = ['user_pass', 'user_activation_key'];
    foreach ($user_table_columns as $column) {
        if (!in_array($column, $excluded_user_fields)) {
            $label = isset($user_field_labels[$column]) 
                ? $user_field_labels[$column] 
                : ucwords(str_replace('_', ' ', $column));
            $all_fields[$column] = $label;
        }
    }
    
    // 2. Get meta keys using existing function (which already applies exclusions)
    $meta_keys = user_elementor_um_get_user_meta_keys();
    
    // Enhanced meta field labels for better display
    $meta_field_labels = [
        'first_name' => 'First Name',
        'last_name' => 'Last Name',
        'nickname' => 'Nickname',
        'description' => 'Biography/Description',
        'birth_date' => 'Birth Date',
        'phone_number' => 'Phone Number',
        'mobile_number' => 'Mobile Number',
        'gender' => 'Gender',
        'country' => 'Country',
        'state' => 'State/Province',
        'city' => 'City',
        'zip_code' => 'ZIP/Postal Code',
        'address' => 'Address',
        'company' => 'Company',
        'position' => 'Job Title/Position',
        'job_title' => 'Job Title',
        'occupation' => 'Occupation',
        'industry' => 'Industry',
        'department' => 'Department',
        'team' => 'Team',
        'manager' => 'Manager',
        'employee_id' => 'Employee ID',
        'student_id' => 'Student ID',
        'course' => 'Course/Program',
        'grade' => 'Grade/Level',
        'graduation_year' => 'Graduation Year',
        'education' => 'Education',
        'experience' => 'Work Experience',
        'skills' => 'Skills',
        'languages' => 'Languages',
        'interests' => 'Interests',
        'about_me' => 'About Me',
        'bio' => 'Bio',
        'age' => 'Age',
        'birthday' => 'Birthday',
        'marital_status' => 'Marital Status',
        'salary' => 'Salary',
        'timezone' => 'Timezone',
        'preferred_language' => 'Preferred Language',
        'date_format' => 'Date Format',
        'time_format' => 'Time Format',
        'currency' => 'Currency',
        'locale' => 'Locale',
        
        // Social Media Fields
        'facebook' => 'Facebook Profile',
        'twitter' => 'Twitter Profile',
        'linkedin' => 'LinkedIn Profile',
        'instagram' => 'Instagram Profile',
        'youtube' => 'YouTube Channel',
        'github' => 'GitHub Profile',
        'skype' => 'Skype ID',
        'telegram' => 'Telegram Username',
        'whatsapp' => 'WhatsApp Number',
        'discord' => 'Discord',
        'social_facebook' => 'Facebook',
        'social_twitter' => 'Twitter',
        'social_linkedin' => 'LinkedIn',
        'social_instagram' => 'Instagram',
        
        // Contact & Location
        'phone' => 'Phone Number',
        'website' => 'Personal Website',
        'profile_photo' => 'Profile Photo',
        'profile_picture' => 'Profile Picture',
        'avatar' => 'Avatar',
        'cover_photo' => 'Cover Photo',
        
        // Account & Status
        'account_status' => 'Account Status',
        'last_login' => 'Last Login',
        'profile_completed' => 'Profile Completion',
        'email_verified' => 'Email Verified',
        'phone_verified' => 'Phone Verified',
        'membership_level' => 'Membership Level',
        'subscription_status' => 'Subscription Status',
        'points' => 'Points/Credits',
        'badge' => 'Badge/Achievement',
        'role' => 'User Role',
        
        // WooCommerce Fields
        'billing_first_name' => 'Billing First Name',
        'billing_last_name' => 'Billing Last Name',
        'billing_email' => 'Billing Email',
        'billing_phone' => 'Billing Phone',
        'billing_address_1' => 'Billing Address Line 1',
        'billing_address_2' => 'Billing Address Line 2',
        'billing_city' => 'Billing City',
        'billing_state' => 'Billing State',
        'billing_postcode' => 'Billing ZIP Code',
        'billing_country' => 'Billing Country',
        'shipping_first_name' => 'Shipping First Name',
        'shipping_last_name' => 'Shipping Last Name',
        'shipping_address_1' => 'Shipping Address Line 1',
        'shipping_address_2' => 'Shipping Address Line 2',
        'shipping_city' => 'Shipping City',
        'shipping_state' => 'Shipping State',
        'shipping_postcode' => 'Shipping ZIP Code',
        'shipping_country' => 'Shipping Country',
        'shipping_phone' => 'Shipping Phone',
    ];
    
    // Add meta fields with enhanced labeling
    foreach ($meta_keys as $meta_key => $value) {
        // Use custom label if available, otherwise format the key intelligently
        if (isset($meta_field_labels[$meta_key])) {
            $label = $meta_field_labels[$meta_key];
        } else {
            // Convert snake_case to Title Case and clean up
            $label = str_replace(['_', '-'], ' ', $meta_key);
            $label = ucwords($label);
            
            // Remove only generic framework-style prefixes; keep semantic prefixes (e.g. Billing/Shipping).
            $label = preg_replace('/^(Um |Wp |Meta |Field )/i', '', $label);
            
            // Handle specific plugin patterns (not WooCommerce billing/shipping — those stay distinct in labels).
            $label = str_replace([
                'Academy ', 'Woocommerce ', 'Elementor ',
                'Pmpro ', 'Bbpress ', 'Buddypress ', 'Learndash ', 'Lifterlms '
            ], '', $label);
        }
        
        $all_fields[$meta_key] = $label;
    }
    
    // 3. Add special computed fields
    $special_fields = [
        'full_name' => 'Full Name (First + Last)',
        'user_avatar' => 'User Avatar',
        'profile_url' => 'Profile URL',
        'registration_date' => 'Registration Date (Formatted)',
    ];
    
    $all_fields = array_merge($all_fields, $special_fields);
    
    // Sort by label for better UX (alphabetical order)
    asort($all_fields);

    set_transient( 'um_ele_meta_keys_combined', $all_fields, HOUR_IN_SECONDS );
    
    return $all_fields;
}

/**
 * Get WordPress user meta keys with human-readable labels
 */
function user_elementor_wp_get_user_meta_keys_combine()
{
    // Use the same function for consistency
    return user_elementor_um_get_user_meta_keys_combine();
}

/**
 * Register widgets
 */
function user_elementor_um_register_widgets( $widgets_manager ): void {
    // Load autoloader first to ensure all dependencies are available
    require_once UM_USER_ELEMENTOR_PATH . 'modules/autoload.php';
    
    // Load widget files
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-user-list.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/wp-user-list.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-user-profile-avatar.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-user-profile-fields.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-user-profile-username.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-user-list-flipbox.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-login-register-styler.php';
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-password-reset-styler.php';

    // ── Pro placeholder widgets (show upgrade card to Free users) ─────────
    require_once UM_USER_ELEMENTOR_PATH . 'modules/um-pro-widget-placeholders.php';
    
    // Register free widgets
    $widgets_manager->register( new \UM_Elementor\UM_ELEMENTOR_LIST_MODULE() );
    $widgets_manager->register( new \UM_Elementor\WP_ELEMENTOR_USER_LIST_MODULE() );
    $widgets_manager->register( new \UM_Elementor\UM_User_Avatar_Widget() );
    $widgets_manager->register( new \UM_Elementor\UM_Profile_Fields_Widget() );
    $widgets_manager->register( new \UM_Elementor\UM_User_Name_Widget() );
    $widgets_manager->register( new \UM_Elementor\UM_ELEMENTOR_LIST_FLIP_MODULE() );
    $widgets_manager->register( new \UM_Elementor\UM_Login_Register_Styler_Widget() );
    $widgets_manager->register( new \UM_Elementor\UM_Password_Reset_Styler_Widget() );

    // Register Pro placeholder widgets
    $widgets_manager->register( new \UM_Elementor\UM_Pro_User_Table_Placeholder() );
    $widgets_manager->register( new \UM_Elementor\UM_Pro_User_Carousel_Placeholder() );
    $widgets_manager->register( new \UM_Elementor\UM_Pro_Advanced_Filters_Placeholder() );
    $widgets_manager->register( new \UM_Elementor\UM_Pro_Profile_Builder_Placeholder() );
    $widgets_manager->register( new \UM_Elementor\UM_Pro_Account_Styler_Placeholder() );
    $widgets_manager->register( new \UM_Elementor\UM_Pro_Multi_Column_Placeholder() );
    $widgets_manager->register( new \UM_Elementor\UM_Pro_Live_Search_Placeholder() );
}

/**
 * Enqueue styles
 */
function user_elementor_um_enqueue_styles(): void {
    // Register main styles
    wp_register_style(
        'um-elementor-styles',
        UM_USER_ELEMENTOR_URL . 'assets/css/ep-elements.css',
        [],
        UM_ELEMENTOR_VERSION
    );
    
    // Register user list styles
    wp_register_style(
        'wp-user-list-styles',
        UM_USER_ELEMENTOR_URL . 'assets/css/wp-user-list.css',
        [],
        UM_ELEMENTOR_VERSION
    );

    // Register profile builder styles
    wp_register_style(
        'umep-profile-builder',
        UM_USER_ELEMENTOR_URL . 'assets/css/um-profile-builder.css',
        [],
        UM_ELEMENTOR_VERSION
    );
}

/**
 * Enqueue editor scripts and styles
 */
function user_elementor_um_enqueue_editor_scripts(): void {
    wp_enqueue_script(
        'um-elementor-editor',
        UM_USER_ELEMENTOR_URL . 'assets/js/ep-elements-editor.js',
        ['jquery'],
        UM_ELEMENTOR_VERSION,
        true
    );

    wp_enqueue_style(
        'um-elementor-editor-styles',
        UM_USER_ELEMENTOR_URL . 'assets/css/um-elementor-editor.css',
        [],
        UM_ELEMENTOR_VERSION
    );
}

/**
 * Load text domain
 */
function user_elementor_um_load_textdomain(): void {
    load_plugin_textdomain(
        'ultimate-member-widgets-for-elementor',
        false,
        dirname(plugin_basename(UM_USER_ELEMENTOR_PATH)) . '/languages'
    );
}

/**
 * Ensure widget scripts are properly enqueued
 */
function um_elementor_enqueue_widget_scripts() {
    // Register user-list.js if not already registered
    if (!wp_script_is('um-user-list-js', 'registered')) {
        wp_register_script(
            'um-user-list-js',
            UM_USER_ELEMENTOR_URL . 'assets/js/user-list.js',
            ['jquery'],
            UM_ELEMENTOR_VERSION,
            true
        );
    }
    
    // Register wp-user-list.js if not already registered
    if (!wp_script_is('wp-user-list-js', 'registered')) {
        wp_register_script(
            'wp-user-list-js',
            UM_USER_ELEMENTOR_URL . 'assets/js/wp-user-list.js',
            ['jquery'],
            UM_ELEMENTOR_VERSION,
            true
        );
    }

    // Localize script for WP User List widget.
    wp_localize_script('wp-user-list-js', 'wp_user_list_ajax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wp_filter_nonce'),
    ]);
}

// Ensure scripts are properly enqueued for widgets
add_action('wp_enqueue_scripts', 'um_elementor_enqueue_widget_scripts');

/**
 * Register editor/preview scripts referenced by widget get_script_depends().
 * Priority 15: before Pro bundle (20) so this extended um-styler-editor wins if both plugins exist.
 */
function user_elementor_um_register_widget_asset_handles(): void {
    if ( ! defined( 'UM_USER_ELEMENTOR_PATH' ) || ! defined( 'UM_USER_ELEMENTOR_URL' ) || ! defined( 'UM_ELEMENTOR_VERSION' ) ) {
        return;
    }
    if ( wp_script_is( 'umep-styler-editor', 'registered' ) ) {
        return;
    }
    $path = UM_USER_ELEMENTOR_PATH . 'assets/js/um-styler-editor.js';
    $ver  = file_exists( $path ) ? (string) filemtime( $path ) : UM_ELEMENTOR_VERSION;
    wp_register_script(
        'umep-styler-editor',
        UM_USER_ELEMENTOR_URL . 'assets/js/um-styler-editor.js',
        [ 'jquery' ],
        $ver,
        true
    );
}
add_action( 'init', 'user_elementor_um_register_widget_asset_handles', 15 );

/**
 * Elementor 4.x: editor v4 and atomic-widgets-editor both register e-flexbox / e-div-block.
 */
function um_elementor_patch_atomic_element_duplicate_registration() {
	if ( ! wp_script_is( 'elementor-editor', 'registered' ) ) {
		return;
	}

	$js = <<<'JS'
(function () {
	if ( ! window.elementor || ! elementor.elementsManager || elementor.elementsManager.__uwepRegisterPatch ) {
		return;
	}
	var manager = elementor.elementsManager;
	var original = manager.registerElementType.bind( manager );
	manager.registerElementType = function ( element ) {
		var type = element.getType();
		if ( manager.elementTypes[ type ] ) {
			return;
		}
		return original( element );
	};
	manager.__uwepRegisterPatch = true;
})();
JS;

	wp_add_inline_script( 'elementor-editor', $js, 'after' );
}
add_action( 'elementor/editor/before_enqueue_scripts', 'um_elementor_patch_atomic_element_duplicate_registration', 1 );

/**
 * Elementor 4.x: editor v4 packages load before their env/settings exist (Pages Panel, Angie MCP).
 */
function um_elementor_editor_v4_compatibility(): void {
	add_filter(
		'elementor/editor/v2/scripts/env',
		static function ( array $env ): array {
			if ( ! isset( $env['@elementor/editor-site-navigation'] ) ) {
				$env['@elementor/editor-site-navigation'] = [
					'is_pages_panel_active' => false,
				];
			}

			return $env;
		}
	);

	if ( ! function_exists( 'is_plugin_active' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	if ( is_plugin_active( 'angie/angie.php' ) ) {
		return;
	}

	add_filter(
		'elementor/editor/v2/packages',
		static function ( array $packages ): array {
			return array_values( array_diff( $packages, [ 'elementor-kit-mcp' ] ) );
		},
		999
	);
}
add_action( 'elementor/init', 'um_elementor_editor_v4_compatibility' );

// Enqueue editor stylesheet on the Elementor preview canvas so placeholder cards are styled.
add_action( 'elementor/preview/enqueue_styles', static function() {
    wp_enqueue_style(
        'um-elementor-editor-styles',
        UM_USER_ELEMENTOR_URL . 'assets/css/um-elementor-editor.css',
        [],
        UM_ELEMENTOR_VERSION
    );
} );

/**
 * Show a one-time Elementor toast when a UM core page still needs a shortcode-to-widget swap.
 */
function um_elementor_enqueue_editor_setup_hint(): void {
	$post_id = absint( $_GET['post'] ?? 0 );
	if ( $post_id < 1 || ! class_exists( '\UM_Elementor\Helpers\UM_Core_Pages' ) ) {
		return;
	}

	$hint = \UM_Elementor\Helpers\UM_Core_Pages::get_editor_setup_hint_data( $post_id );
	if ( ! $hint || ! wp_script_is( 'elementor-editor', 'registered' ) ) {
		return;
	}

	if ( class_exists( '\Elementor\User' ) ) {
		$dismissed = \Elementor\User::get_dismissed_editor_notices();
		if ( is_array( $dismissed ) && in_array( $hint['dismiss_id'], $dismissed, true ) ) {
			return;
		}
	}

	wp_enqueue_script( 'elementor-editor' );

	$payload = wp_json_encode( $hint );
	if ( ! is_string( $payload ) ) {
		return;
	}

	$js = <<<JS
(function () {
	var hint = {$payload};

	function isDismissed() {
		var dismissed = (window.elementor && elementor.config && elementor.config.user && elementor.config.user.dismissed_editor_notices) || [];
		return dismissed.indexOf(hint.dismiss_id) !== -1;
	}

	function dismissHint() {
		if (!window.elementorCommon || !elementorCommon.ajax) {
			return;
		}
		elementorCommon.ajax.addRequest('dismissed_editor_notices', {
			data: { dismissId: hint.dismiss_id }
		});
		if (elementor.config && elementor.config.user) {
			elementor.config.user.dismissed_editor_notices = elementor.config.user.dismissed_editor_notices || [];
			elementor.config.user.dismissed_editor_notices.push(hint.dismiss_id);
		}
	}

	function showHint() {
		if (!window.elementor || !elementor.notifications || isDismissed()) {
			return;
		}
		elementor.notifications.showToast({
			message: hint.message,
			buttons: [{
				name: 'dismiss',
				text: hint.dismiss_label || 'Got it',
				callback: dismissHint
			}]
		});
	}

	if (window.jQuery) {
		jQuery(window).on('elementor:init', showHint);
	}
})();
JS;

	wp_add_inline_script( 'elementor-editor', $js, 'after' );
}
add_action( 'elementor/editor/before_enqueue_scripts', 'um_elementor_enqueue_editor_setup_hint', 30 );

/**
 * Post ID for the page open in Elementor (editor shell or preview iframe).
 */
function um_elementor_get_edited_post_id_for_notice(): int {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Elementor preview iframe query arg.
	$preview_id = isset( $_GET['elementor-preview'] ) ? absint( $_GET['elementor-preview'] ) : 0;
	if ( $preview_id > 0 ) {
		return $preview_id;
	}

	if ( ! class_exists( '\Elementor\Plugin' ) ) {
		return (int) get_the_ID();
	}

	$plugin = \Elementor\Plugin::$instance;
	if ( is_object( $plugin->preview ) && $plugin->preview->is_preview_mode() ) {
		$post_id = (int) $plugin->preview->get_post_id();
		if ( $post_id > 0 ) {
			return $post_id;
		}
	}
	if ( is_object( $plugin->editor ) && $plugin->editor->is_edit_mode() ) {
		$post_id = (int) $plugin->editor->get_post_id();
		if ( $post_id > 0 ) {
			return $post_id;
		}
	}

	return (int) get_the_ID();
}

/**
 * True when serving the Elementor canvas: editor AJAX render or preview iframe request.
 *
 * @return bool
 */
function umwfe_is_elementor_design_surface(): bool {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Elementor preview iframe query arg.
	if ( isset( $_GET['elementor-preview'] ) && absint( $_GET['elementor-preview'] ) > 0 ) {
		return true;
	}

	if ( ! class_exists( '\Elementor\Plugin' ) ) {
		return false;
	}

	$plugin = \Elementor\Plugin::$instance;
	if ( is_object( $plugin->preview ) && method_exists( $plugin->preview, 'is_preview' ) && $plugin->preview->is_preview() ) {
		return true;
	}
	if ( is_object( $plugin->editor ) && $plugin->editor->is_edit_mode() ) {
		return true;
	}
	if ( is_object( $plugin->preview ) && $plugin->preview->is_preview_mode() ) {
		return true;
	}

	return false;
}

/**
 * Prepends a canvas swap notice when UM shortcodes render in the Elementor editor preview.
 *
 * @param string $output Shortcode HTML.
 * @param string $tag    Shortcode tag.
 * @param array  $attr   Shortcode attributes.
 * @param array  $m      Regex match from get_shortcode_regex().
 */
function um_elementor_prepend_shortcode_canvas_notice( string $output, string $tag, array $attr, array $m ): string {
	$um_shortcode_tags = [ 'ultimatemember', 'ultimatemember_account', 'ultimatemember_password' ];
	if ( ! in_array( $tag, $um_shortcode_tags, true ) ) {
		return $output;
	}
	if ( ! umwfe_is_elementor_design_surface() ) {
		return $output;
	}
	if ( ! class_exists( '\UM_Elementor\Helpers\UM_Core_Pages' ) || ! class_exists( '\UM_Elementor\Helpers\UM_Editor_Placeholder' ) ) {
		return $output;
	}

	$notice = \UM_Elementor\Helpers\UM_Core_Pages::get_shortcode_canvas_notice_data(
		um_elementor_get_edited_post_id_for_notice()
	);
	if ( ! $notice ) {
		return $output;
	}

	return \UM_Elementor\Helpers\UM_Editor_Placeholder::canvas_notice_html(
		$notice['title'],
		$notice['message']
	) . $output;
}
add_filter( 'do_shortcode_tag', 'um_elementor_prepend_shortcode_canvas_notice', 10, 4 );

add_action( 'init', 'user_elementor_um_load_textdomain' );

add_action( 'updated_user_meta', 'user_elementor_um_delete_meta_keys_cache' );

// ── Boot Pro Conversion Triggers (slim widget-count notice + placeholder wiring) ──
require_once UM_USER_ELEMENTOR_PATH . 'inc/class-um-elementor-pro-links.php';
require_once UM_USER_ELEMENTOR_PATH . 'inc/class-pro-conversion.php';
add_action( 'plugins_loaded', static function() {
    new UM_Elementor_Pro_Conversion();
} );



