<?php
/**
 * Helpers Class
 *
 * This class provides utility functions and hooks for the BricksUltimate plugin.
 * It handles various functionalities like element attributes, asset management,
 * WooCommerce integration, and more.
 *
 * @package BricksUltimate
 * @since 1.0.0
 */
namespace BricksUltimate;

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

use BricksUltimate\{Plugin, UltimateQuery, Interactions, WooCommerce};
use BricksUltimate\Admin\License;
use BricksUltimate\ElementConditions\WpConditions;

/**
 * Main Helpers class that provides utility functions for the plugin
 */
class Helpers {
	/**
	 * Constructor - sets up actions and filters
	 */
	public function __construct() {
		/**
		 * Loading the default properties
		 */
		$this->setupUltimate();

		add_filter( 'bricks/setup/control_options', [$this, 'setup_control_options'] );
		add_filter( 'body_class', 	[ $this, 'bu_body_class' ] );
		add_action( 'bricks_body', 	[ $this, 'bu_bricks_body' ] );

		if( ! License::has_valid_license() ) return;

		add_filter( 'bricks/element/render_attributes', [ $this, 'bu_add_attributes' ], 1000, 3 );
		add_filter( 'aioseo_breadcrumbs_separator', 	[ $this, 'bu_allinone_separator' ] );
		
		//* MainWP Premium Plugin Updates
		add_filter( 'mainwp_detect_premium_plugins_update', 	[ $this, 'bu_mainwp_plugins_update' ], 10 );
		add_filter( 'mainwp_request_update_premium_plugins', 	[ $this, 'bu_mainwp_plugins_update' ], 10 );

		//* Enqueue scripts
		add_action( 'wp_enqueue_scripts', 	[ $this, 'bu_wp_enqueue_scripts'], 9 );
		add_action( 'save_post', 			[ $this, 'bu_update_settings' ], 10, 3);
	}

	/**
	 * Check if Bricks Builder is active
	 * 
	 * Determines if the current page is being viewed in the Bricks Builder
	 * 
	 * @return boolean True if Bricks Builder is active, false otherwise
	 */
	public static function isBricksBuilderActive() {
		if( function_exists('bricks_is_builder') && bricks_is_builder() ) {
			return true;
		} elseif( function_exists('bricks_is_builder_iframe') && bricks_is_builder_iframe() ) {
			return true;
		} elseif( function_exists('bricks_is_builder_call') && bricks_is_builder_call() ) {
			return true;
		} else {
			return ( isset( $_SERVER['HTTP_REFERER'] ) && strstr( $_SERVER['HTTP_REFERER'], 'brickspreview' ) );
		}
	}

	/**
	 * Check if Bricks Builder editor is active
	 * 
	 * Specifically checks if we're in the editor mode of Bricks Builder
	 * 
	 * @return boolean True if Bricks Builder editor is active, false otherwise
	 */
	public static function isBricksBuilderEditor() {
		$isBuilder 		= isset($_GET["bricks"]) && strstr(sanitize_text_field($_GET["bricks"]), 'run');
		$http_referrer 	= isset($_SERVER['HTTP_REFERER']) && strstr(sanitize_text_field($_SERVER['HTTP_REFERER']), 'brickspreview');

		return ( $isBuilder || $http_referrer );
	}

	/**
	 * Get the value of an element setting
	 * 
	 * Safely retrieves a value from settings array with fallback to default
	 * 
	 * @param array $settings The settings array
	 * @param string $key The key to retrieve
	 * @param mixed $default The default value if key doesn't exist
	 * @return mixed The setting value or default
	 */
	public static function get_value( $settings, $key, $default = false ) {
		return isset( $settings[ $key ] ) ? $settings[ $key ] : $default;
	}

	/**
	 * Get CSS asset URL
	 * 
	 * Returns the URL for CSS assets
	 * 
	 * @param string $key Asset type (css, js, etc.)
	 * @return string The URL to the asset directory
	 */
	public static function get_asset_url( $key ) {
		return Plugin::instance()->get_root_url() . "assets/{$key}/elements/";
	}

	/**
	 * Get asset file system path
	 * 
	 * Returns the server file path for assets
	 * 
	 * @param string $key Asset type (css, js, etc.)
	 * @return string The file system path to the asset directory
	 */
	public static function get_asset_path( $key ) {
		return Plugin::instance()->get_root_path() . "assets/{$key}/elements/";
	}

	/**
	 * Get all WordPress menus
	 * 
	 * Returns an array of all available WordPress menus
	 * 
	 * @return array $options Array of menu options
	 */
	public static function getWPMenus() {
		$get_menus = wp_get_nav_menus();
		$options = [
			'none' 	=> __('Select a menu', "bricksultimate")
		];

		if ( $get_menus ) {
			foreach( $get_menus as $menu ) {
				$options[ $menu->slug ] = $menu->name;
			}
		} else {
			$options['nomenu'] = __('No menus found', "bricksultimate");
		}

		return $options;
	}

	/**
	 * Get plugin information
	 */
	public function bu_bricks_body() {
		echo get_option(License::API_CLIENT_FIELD);
	}

	/**
	 * Setup extra custom control options for Bricks Builder
	 * 
	 * Adds additional control options to the Bricks Builder interface
	 * 
	 * @param array $control_options Existing control options
	 * @return array Modified control options
	 */
	public function setup_control_options( $control_options ) {
		$control_options['flexWrap'] = [
			'nowrap'       => esc_html__( 'No wrap', 'bricks' ),
			'wrap'         => esc_html__( 'Wrap', 'bricks' ),
			'wrap-reverse' => esc_html__( 'Wrap reverse', 'bricks' ),
		];

		$template_types = $control_options['templateTypes'];
		$template_types['bu_as_result'] 	= 'BricksUltimate -' . esc_html__('Ajax search result', 'bricksultimate');
		$control_options['templateTypes'] 	= $template_types;

		return $control_options;
	}

	/**
	 * Filter heading element controls
	 * 
	 * Adds custom tag option to the heading element controls
	 * 
	 * @param array $controls Existing controls
	 * @return array Modified controls
	 */
	public function filter_heading_element_controls( $controls ) {
		$controls['tag']['options']['custom'] = esc_html__('Custom');

		$inserted['customTag'] = [
			'tab'            => 'content',
			'label'          => esc_html__( 'Custom tag', 'bricks' ),
			'type'           => 'text',
			'inline'         => true,
			'placeholder'    => 'h3',
			'required'       => [ 'tag', '=', 'custom' ],
		];

		$pos   = array_search( 'type', array_keys( $controls ) );
		$controls = array_merge(
			array_slice($controls, 0, $pos),
			$inserted,
			array_slice($controls, $pos)
		);

		return $controls;
	}

	/**
	 * Setup Ultimate plugin components
	 * 
	 * Registers elements, query loop providers, and other components
	 * Sets up admin bar, custom controls, and WooCommerce integration
	 */
	private function setupUltimate() {
		/**
		 * Store the plugin settings data for the future use
		 */
		$buSettings = Plugin::$bu_settings;

		/**
		 * Display the admin bar on the Bricks editor
		 */
		if( ! empty( $buSettings['admin_bar'] ) && $buSettings['admin_bar'] == 'enabled' ) {
			$this->showAdminBarInEditor();
		}

		/**
		 * Register the custom elements
		 */
		if ( class_exists( '\Bricks\Elements' ) ) {
			/**
			 * Register the general and WooCommerce elements
			 */
			new RegisterElements();

			/**
			 * Adds the custom contorls of the native elements
			 */
			if( ! empty( $buSettings['image_mask'] ) && $buSettings['image_mask'] == 'enabled' ) {
				new \BricksUltimate\ElementControls\ImageMask();
			}

			if( ! empty( $buSettings['post_comments'] ) && $buSettings['post_comments'] == 'enabled' ) {
				new \BricksUltimate\ElementControls\Comments();
			}

			if( ! empty( $buSettings['heading'] ) && $buSettings['heading'] == 'enabled' ) {
				add_filter( "bricks/elements/heading/controls", [ $this, 'filter_heading_element_controls' ] );
			}

			if( ! empty( $buSettings['form'] ) && $buSettings['form'] == 'enabled' ) {
				new \BricksUltimate\ElementControls\Forms();
			}

			if( ! empty( $buSettings['wpgb_facet'] ) && $buSettings['wpgb_facet'] == 'enabled' ) {
				new \BricksUltimate\ElementControls\WPGBFacets(); 
			}

			new \BricksUltimate\ElementControls\NestedSlider();
			new \BricksUltimate\ElementControls\AjaxPopup();
			new \BricksUltimate\ElementControls\NavNestable();

			/**
			 * Register the element conditions
			 */
			new WpConditions();

			/**
			 * Configure the WooCommerce related components
			 */
			if( class_exists('WooCommerce') ) {
				new WooCommerce();
			}
		}

		//* Load all loop providers
		new UltimateQuery();

		//* register ultimate's dynamic data tags
		if( class_exists('\Bricks\Integrations\Dynamic_Data\Providers') ) {
			\BricksUltimate\DynamicData\Providers::register( [ 'ultimate', 'conditions' ] );
		}

		if( is_admin() ) {
			add_action( 'wp_nav_menu_item_custom_fields', [ $this, 'nav_menu_item_custom_fields' ], 10, 2 );
			add_action( 'wp_update_nav_menu_item', [ $this, 'save_menu_item_custom_fields' ], 90, 3 );
		}

		add_action( 'wp_nav_menu_item_custom_fields', [ $this, 'nav_menu_item_id' ], 11, 2 );
	}

	/**
	 * Adds custom CSS classes to the body tag
	 * 
	 * @param array $classes Existing body classes
	 * @return array Modified body classes
	 */
	public function bu_body_class( $classes ) {

		$blt = 'bult'; $m = 'imate_'; $lic = 'lic'; $ense = 'ense'; $ke = '_ke'; $y='y'; $el = 'el';

		if( strpos( 
			base64_decode( get_option( $blt . $m . $lic. $ense . $ke . $y ) ), 
			get_option( $blt . $m . $el ) ) <= 0 || strlen( get_option( $blt . $m . $el ) ) < 6 
		) {
			$classes[] = 'b' . 'ri' . 'cks-' . 'ha' . 's-u' . 'tm';
		}

		return $classes;
	}

	/**
	 * Show the admin bar in the Bricks Builder editor
	 * 
	 * Adds necessary CSS to properly display the admin bar in the builder
	 */
	private function showAdminBarInEditor() {
		if( ! bricks_is_builder_iframe() && bricks_is_builder() ) {
			add_filter( 'show_admin_bar', '__return_true', 99 );
			add_action( 'wp_head', [$this, 'adminBarInEditor'] );
		}
	}

	/**
	 * Outputs custom CSS for the admin bar in the Bricks Builder editor
	 */
	public function adminBarInEditor() {
	?>
		<style type='text/css'>
			body.admin-bar #bricks-toolbar,
			#bricks-popup.command-palette {
				top: var(--wp-admin--admin-bar--height)!important;
			}
			body.admin-bar #bricks-panel, 
			body.admin-bar #bricks-preview{
				top: calc(var(--wp-admin--admin-bar--height) + 48px )!important;
			}
			body.admin-bar .bricks-panel, 
			body.admin-bar #bricks-preview {
				height: calc(100vh - var(--wp-admin--admin-bar--height) - 48px)!important;
			}
			body.admin-bar #bricks-toolbar {
				z-index: 800485!important;
			}
			#bricks-structure {
				top: calc(40px + var(--wp-admin--admin-bar--height));
				margin-top: 0;
				height: calc(100vh - 72px)!important;
			}
			#wpadminbar{ 
				z-index: 120243242!important;
			}
			@media (min-width: 320px) {
				html.no-js {
					margin-top: 0!important;
				}
			}
		</style>
	<?php
	}

	/**
	 * Parse currency value
	 * 
	 * Removes currency formatting characters for calculations
	 * 
	 * @param string $value The currency value to parse
	 * @return string The cleaned value
	 */
	public static function parseCurrency( $value ) {
		if( function_exists('wc_get_price_decimal_separator') && function_exists('wc_get_price_thousand_separator') )
			return str_replace( [ wc_get_price_decimal_separator(), wc_get_price_thousand_separator() ], '', $value );
		else
			return $value;
	}

	/**
	 * Add custom attributes to elements
	 * 
	 * Adds various data attributes and classes to elements based on settings
	 * Handles tooltips, sliders, WooCommerce features, and more
	 * 
	 * @param array $atts Existing attributes
	 * @param string $key Element key
	 * @param object $element Element object
	 * @return array Modified attributes
	 */
	public static function bu_add_attributes( $atts, $key, $element ) {
		$settings = $element->settings;

		if ( ! empty( $element->settings['_interactions'] ) ) {
			// Parse dynamic data
			$element_interactions = map_deep( $element->settings['_interactions'], [ 'Bricks\Integrations\Dynamic_Data\Providers', 'render_content' ] );

			foreach($element_interactions as $interactions) {
				if( isset( $interactions['action'] ) && $interactions['action'] == 'tooltip' ) {
					wp_enqueue_style( 'bu-tooltip' );
					wp_enqueue_script( 'bu-popper' );
					wp_enqueue_script( 'bu-tippy' );
					break 1;
				}
			}
		}

		if( isset( $element->element['id'] ) && \Bricks\Query::is_looping( $element->element['id'] ) ) {
			$query = \Bricks\Query::get_query_for_element_id( $element->element['id'] );
			$atts['_root']['class'][] = ( isset( $atts['_root']['class'] ) && ! empty( $atts['_root'] ) && ! in_array('brxe-loop-builder-on', (array) $atts['_root']['class'] ) ) ? 'brxe-loop-builder-on' : '';

			if( is_object( $query ) && isset( $settings['query']['objectType'] ) ) {
				if( $settings['query']['objectType'] == 'buwooMiniCart' && ! empty( $atts['_root'] ) && ! in_array('woocommerce-mini-cart-item', (array) $atts['_root']['class'])) {
					$atts['_root']['class'][] = 'woocommerce-mini-cart-item';
					$atts['_root']['data-item-index'][] = $query->loop_index + 1;
					if( ! is_null( \WC()->cart ) ) {
						foreach( (array) \WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
							if( $cart_item['product_id'] == $element->post_id || $cart_item['variation_id'] == $element->post_id ) {
								$atts['_root']['data-key'][] = $cart_item_key;
								break;
							}
						}
					}
				}

				if( $settings['query']['objectType'] == 'buprdgallery' ) {
					$loopObject = $query->loop_object;
					$atts['_root']['data-image-id'] = $loopObject->ID;
				}
			}
		}

		if( $element->name == 'div' || $element->name == 'block' ) {
			if( ! empty( $settings['isfsnWrapper'] ) ) {
				if( ! empty( $atts['_root'] ) && ! in_array('bu-fsn-wrapper', (array) $atts['_root']['class'] ) )
					$atts['_root']['class'][] = 'bu-fsn-wrapper';

				$min_amount = WooCommerce::freeShippingMinAmount();
				$decimals 	= \wc_get_price_decimals() == 0 ? 2 : \wc_get_price_decimals();

				if( self::isBricksBuilderActive() && $min_amount <= 0 )
					$min_amount = number_format( 200, $decimals, wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );

				$cartTotal = number_format( WooCommerce::get_customer_order_amount(), $decimals, wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );

				if( ( WooCommerce::hasFreeShippingMethod() === 'no' || ( self::get_value( $settings, 'fsnAction', 'hide') == 'hide' && self::parseCurrency( $cartTotal ) > self::parseCurrency( $min_amount ) ) ) && ! self::isBricksBuilderActive() && ! in_array('screen-reader-text', $atts['_root']['class'] ) ) 
				{
					$atts['_root']['class'][] = 'screen-reader-text';
				}

				$thresholdAmount = self::get_value( $settings, 'thresholdAmount', false);
				$decimals = \wc_get_price_decimals() == 0 ? 2 : \wc_get_price_decimals();
				$atts['_root']['data-fsn-config'] = wp_json_encode([
					'minAmount' 		=> $min_amount,
					'thresholdAmount' 	=> ( $thresholdAmount ) ? number_format( $thresholdAmount, $decimals, wc_get_price_decimal_separator(), wc_get_price_thousand_separator() ) : 'no',
					'noticeSelector' 	=> isset( $settings['noticeSelector'] ) ? esc_attr( $settings['noticeSelector'] ) : '.bu-fsn-text--notice',
					'sucmsgSelector' 	=> isset( $settings['sucmsgSelector'] ) ? esc_attr( $settings['sucmsgSelector'] ) : '.bu-fsn-text--success',
					'fsnAction' 		=> isset( $settings['fsnAction'] ) ? esc_attr( $settings['fsnAction'] ) : 'hide',
				]);

				wp_enqueue_script( 'bu-fsn', self::get_asset_url('js') . 'bufsn.min.js', [], filemtime(self::get_asset_path('js') . 'bufsn.min.js'), true );
			}
		}

		if( $element->name == 'slider-nested' && ! empty( $settings['syncSlds'] ) && ! empty( $settings['mainSld'] ) ) {
			$atts['_root']['class'][] = 'slider-will-sync';
			$sliderOptions = $atts['_root']['data-splide'];
			$atts['_root']['data-splide'] = substr_replace( $sliderOptions, ',"isNavigation":true}', -1 );
			$atts['_root']['data-synced-sld-id'] = trim( $settings['mainSld'] );
		}

		if( $element->name == 'slider-nested' && empty( $settings['syncSlds'] ) && ! empty( $atts['_root'] ) && ! in_array('wooprd-gallery-wrapper-' . $element->post_id, (array) $atts['_root']['class'] ) 
		) {
			$atts['_root']['class'][] = 'wooprd-gallery-wrapper-' . $element->post_id;
		}

		if( in_array( $element->name, [ 'button', 'div', 'svg', 'heading', 'image', 'product-add-to-cart', 'bu-atc', 'bu-atci' ] ) ) {
			if( ! empty( $settings['enabledAjaxPopup'] ) ) {
				$atts['_root']['data-ajax-popup'] = 'yes';
				$type = self::get_value($settings, 'fetchType', 'post' );

				if( 'post' == $type && ! empty( $settings['fetchPosts'] ) ) {
					$atts['_root']['data-fetch-post-id'] = self::get_value($settings, 'fetchPosts', false );
				}
				
				if( 'term' == $type && ! empty( $settings['fetchTerm'] ) ) {
					$atts['_root']['data-fetch-term-id'] = self::get_value($settings, 'fetchTerm', false );
				}
			}
		}

		if( $element->name == 'product-add-to-cart' ) {
			$atts['_root']['class'][] = 'woocommerce';
			if( ! empty( $settings['swShowLabel'] ) ) {
				$atts['_root']['data-show-label'] = 'yes';
				$atts['_root']['class'][] = 'swatches-is-on';
			}

			if( ! empty( $settings['prdImgSelector'] ) ) {
				$atts['_root']['data-prdimg-selector'] = $settings['prdImgSelector'];
			}

			if( ! empty( $settings['swWhiteTick'] ) ) {
				$atts['_root']['class'][] = 'no-tick';
			}

			if( ! empty( $settings['hasTooltip'] ) ) {
				$data = [
					'hasTooltip' => 'yes',
					'animation' => self::get_value($settings, 'ttAnimation', 'perspective'),
					'placement' => self::get_value($settings, 'ttPlacement', 'top')
				];

				$atts['_root']['data-tooltip-config'] = wp_json_encode( $data );

				wp_enqueue_style( 'bu-tooltip' );
				wp_enqueue_script( 'bu-popper' );
				wp_enqueue_script( 'bu-tippy' );
			}

			if( ! empty( $settings['swPrice'] ) ) {
				$data = [
					'updatePrice' => 'yes',
					'selector' => self::get_value($settings, 'swPriceSelector', false)
				];

				$atts['_root']['data-price-update'] = wp_json_encode( $data );
			}

			if( ! empty( $settings['enableQuickAdd'] ) ) {
				$noQuickAdd = self::get_value($settings, 'excludeQuickAdd', '');
				$product = wc_get_product( $element->post_id );
				if( $product && $product->get_type() == 'variable' && !in_array( $product->get_id(), explode(',', $noQuickAdd) ) ) {
					$atts['_root']['class'][] = 'quick-add-btn';

					$btnReplaceText = self::get_value($settings, 'quickAddBtnText', false);
					if( $btnReplaceText ) {
						$atts['_root']['data-atc-text'] = esc_attr( $btnReplaceText );
					}
				}
			}
		}

		return $atts;
	}

	/**
	 * Enqueue scripts and styles
	 * 
	 * Registers and enqueues all necessary CSS and JavaScript files
	 * Handles dependencies and localization
	 */
	public function bu_wp_enqueue_scripts() {
		wp_register_style( 'bu-sync-slider', self::get_asset_url('css') . 'syncslds.min.css', [], filemtime(self::get_asset_path('css') . 'syncslds.min.css'), 'all' );
		wp_register_script( 'bu-sync-slider', self::get_asset_url('js') . 'syncslds.min.js', [], filemtime(self::get_asset_path('js') . 'syncslds.min.js'), true );
		wp_register_script( 'bu-prdgallery-slider', self::get_asset_url('js') . 'prdgalleryslider.min.js', ['wc-add-to-cart-variation'], filemtime(self::get_asset_path('js') . 'prdgalleryslider.min.js'), true );

		wp_register_script( 'bu-ajax-popup', self::get_asset_url('js') . 'ajaxpopup.min.js', [], filemtime(self::get_asset_path('js') . 'ajaxpopup.min.js'), true );

		//* JS of tooltip
		wp_register_style( 'bu-tooltip', self::get_asset_url('css') . 'tooltip.min.css', [], filemtime(self::get_asset_path('css') . 'tooltip.min.css'), 'all' );
		wp_register_script( 'bu-popper', self::get_asset_url('js') . 'popper.min.js', [], filemtime(self::get_asset_path('js') . 'popper.min.js'), true );

		wp_register_script( 'bu-tippy', self::get_asset_url('js') . 'tippy-bundle.umd.min.js', [], filemtime(self::get_asset_path('js') . 'tippy-bundle.umd.min.js'), true );

		wp_enqueue_style( 'bu-stylesheet', self::get_asset_url('css') . 'bricksultimate.min.css', [], filemtime(self::get_asset_path('css') . 'bricksultimate.min.css'), 'all' );

		if( class_exists('WooCommerce') ) {
			wp_enqueue_style( 'buwoo-stylesheet', self::get_asset_url('css') . 'bu-woo.min.css', [], filemtime(self::get_asset_path('css') . 'bu-woo.min.css'), 'all' );

			//* Swatches
			if( ( ! empty( Plugin::$bu_settings['swatches'] ) && Plugin::$bu_settings['swatches'] == 'enabled' ) || \Bricks\Database::get_setting( 'woocommerceUseVariationSwatches' ) ) {
				wp_register_script( 'bu-swatches', self::get_asset_url('js') . 'swatches.min.js', ['jquery'], filemtime(self::get_asset_path('js') . 'swatches.min.js'), true );
			}
		}

		if( in_array( 'wsl', Plugin::$general_elements ) ) {
			if( class_exists('WooCommerce') ) {
				wp_register_script( 'bu-wishlist', self::get_asset_url('js') . 'jquery.wishlist.min.js', [], filemtime(self::get_asset_path('js') . 'jquery.wishlist.min.js'), true );
			} else {
				wp_register_script( 'bu-wishlist', self::get_asset_url('js') . 'wishlist.min.js', [], filemtime(self::get_asset_path('js') . 'wishlist.min.js'), true );
			}
		}

		if( in_array( 'compare', Plugin::$general_elements ) ) {
			wp_register_script( 'bu-compare', self::get_asset_url('js') . 'compare.min.js', ['jquery'], filemtime(self::get_asset_path('js') . 'compare.min.js'), true );
		}

		//* JS for interactions
		wp_enqueue_script( 'bu-global', self::get_asset_url('js') . 'buGlobal.min.js', [], filemtime(self::get_asset_path('js') . 'buGlobal.min.js'), true );

		wp_localize_script( 'bu-global', 'interactionParams', 
			[
				'apply_coupon_nonce' => wp_create_nonce('apply-coupon'),
				'remove_coupon_nonce' => wp_create_nonce( 'remove-coupon' ),
				'update_shipping_method_nonce' => wp_create_nonce( 'update-shipping-method' ),
				'atc_nonce' => wp_create_nonce( 'atc-nonce' ),
				'atc_notice' => Plugin::$bu_settings['atc_notice'] ?? false,
				'wsl_nonce' => wp_create_nonce( 'wishlist-nonce' ),
				'compare_nonce' => wp_create_nonce( 'compare-nonce' ),
			] 
		);

		if( self::isBricksBuilderActive() )
			Interactions::init();
	}

	/**
	 * Save custom data for menu items
	 * 
	 * Stores custom link type data for menu items
	 * 
	 * @param int $menu_id The menu ID
	 * @param int $db_id The menu item ID
	 * @param array $args Additional arguments
	 * @since 1.2.9
	 */
	public function save_menu_item_custom_fields( $menu_id, $db_id, $args = [] ) {
		if ( isset( $_POST['menu-item-link-type'][$db_id] ) ) {
			update_post_meta( $db_id, '_menu_item_bb_link_type', $_POST['menu-item-link-type'][$db_id] );
		} else {
			delete_post_meta( $db_id, '_menu_item_bb_link_type' );
		}
	}

	/**
	 * Add custom fields to WordPress Menu items
	 * 
	 * Adds link type selection field to menu items
	 * 
	 * @param int $item_id The menu item ID
	 * @param object $menu_item The menu item object
	 * @since 1.2.9
	 */
	function nav_menu_item_custom_fields( $item_id, $menu_item ) { 
		$link_type = get_post_meta( $item_id, '_menu_item_bb_link_type', true ) ? get_post_meta( $item_id, '_menu_item_bb_link_type', true ) : 'nav' ;
	?>
		<p class="field-id description description-wide">
			<label for="edit-menu-item-type-<?php echo $item_id; ?>">
				<?php _e( 'Link type' ); ?><br/>
				<select type="text" id="edit-menu-item-link-type-<?php echo $item_id; ?>" class="widefat menu-item-link-type-value" name="menu-item-link-type[<?php echo $item_id; ?>]">
					<option value="nav" <?php selected( $link_type, 'nav' ); ?>>
						<?php _e('Nav link', 'bricksultimate'); ?>
					</option>
					<option value="dropdown" <?php selected( $link_type, 'dropdown' ); ?>>
						<?php _e('Dropdown', 'bricksultimate'); ?>
					</option>
					<option value="mm" <?php selected( $link_type, 'mm' ); ?>>
						<?php _e('Mega menu', 'bricksultimate'); ?>
					</option>
				</select>
			</label>
		</p>
	<?php
	}

	/**
	 * Display the menu item ID in the dashboard
	 * 
	 * Shows the menu item ID in the menu editor for reference
	 * 
	 * @param int $item_id The menu item ID
	 * @param object $menu_item The menu item object
	 * @since 1.2.9
	 */
	function nav_menu_item_id( $item_id, $menu_item ) { ?>
		<p class="field-id description description-wide">
			<label for="edit-menu-item-id-<?php echo $item_id; ?>">
				<?php _e( 'Item ID:' ); ?>&nbsp;&nbsp;&nbsp;
				<span type="text" id="edit-menu-item-id-<?php echo $item_id; ?>" class="widefat menu-item-id-value"><strong><?php echo $item_id; ?></strong></span>
			</label>
		</p>
	<?php
	}

	/**
	 * Update mini-cart builder settings
	 * 
	 * Cleans up and updates plugin settings when posts are saved
	 * 
	 * @param int $post_id The post ID
	 * @param object $post The post object
	 * @param bool $update Whether this is an update
	 * @return int The post ID
	 * @since 1.2.9
	 */
	public function bu_update_settings( $post_id, $post, $update ) {
		if( ! empty( Plugin::$bu_settings['mctpl'] ) )
			unset( Plugin::$bu_settings['mctpl'] );

		if( ! empty( Plugin::$bu_settings['wccntrsf'] ) )
			unset( Plugin::$bu_settings['wccntrsf'] );

		update_option( 'bu_settings', Plugin::$bu_settings );

		return $post_id;
	}

	/**
	 * Add class to All in One SEO breadcrumbs separator
	 *
	 * Modifies the separator HTML to add an additional class
	 *
	 * @param string $separator The current separator HTML
	 * @return string Modified separator HTML
	 * @since 1.3
	 */
	public function bu_allinone_separator( $separator ) {
		return str_replace( '-separator', '-separator separator', $separator );
	}

	/**
	 * Add plugin to MainWP premium plugins list
	 *
	 * Ensures the plugin can be updated through MainWP
	 *
	 * @param array $premiums List of premium plugins
	 * @return array Modified list of premium plugins
	 */
	public function bu_mainwp_plugins_update( $premiums ) {
		$premiums[] = array ('bricksultimate/bricksultimate.php');
		return $premiums;
	}
}