<?php
namespace Sifency_Addons\Includes\Elementor;

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

	public function __construct() {
		add_action( 'elementor/elements/categories_registered', array( $this, 'register_widget_categories' ) );
		add_action( 'elementor/widgets/register', array( $this, 'register_widgets' ) );
	}

	/**
	 * Registers custom widget categories for Elementor.
	 */
	public function register_widget_categories( $elements_manager ) {

		$elements_manager->add_category(
			'sifency-typography-widgets',
			array(
				'title' => esc_html__( 'Sifency Typography', 'sifency-addons' ),
				'icon'  => 'eicon-plug',
			)
		);
		$elements_manager->add_category(
			'sifency-business-widgets',
			array(
				'title' => esc_html__( 'Sifency Business', 'sifency-addons' ),
				'icon'  => 'eicon-plug',
			)
		);
		$elements_manager->add_category(
			'sifency-creative-widgets',
			array(
				'title' => esc_html__( 'Sifency Creative', 'sifency-addons' ),
				'icon'  => 'eicon-plug',
			)
		);
		$elements_manager->add_category(
			'sifency-addons-widgets',
			array(
				'title' => esc_html__( 'Sifency Addons', 'sifency-addons' ),
				'icon'  => 'eicon-plug',
			)
		);

		$elements_manager->add_category(
			'sifency-advance-widgets',
			array(
				'title' => esc_html__( 'Sifency Advance', 'sifency-addons' ),
				'icon'  => 'eicon-plug',
			)
		);
		$elements_manager->add_category(
			'sifency-post-components',
			array(
				'title' => esc_html__( 'Sifency Post Components', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		if ( class_exists( 'WooCommerce' ) ) {
			$elements_manager->add_category(
				'sifency-addons-woo-widgets',
				array(
					'title' => esc_html__( 'Sifency WooCommerce', 'sifency-addons' ),
					'icon'  => 'eicon-woocommerce',
				)
			);
		}
		$elements_manager->add_category(
			'member-post-components',
			array(
				'title' => esc_html__( 'Sifency Member Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-event-components',
			array(
				'title' => esc_html__( 'Sifency Event Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-career-components',
			array(
				'title' => esc_html__( 'Sifency Career Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-portfolio-components',
			array(
				'title' => esc_html__( 'Sifency Portfolio Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-document-components',
			array(
				'title' => esc_html__( 'Sifency Docs Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-service-components',
			array(
				'title' => esc_html__( 'Sifency Service Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-digital-components',
			array(
				'title' => esc_html__( 'Sifency Digital Goods Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-doc-components',
			array(
				'title' => esc_html__( 'Sifency Doc Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
		$elements_manager->add_category(
			'sifency-edd-components',
			array(
				'title' => esc_html__( 'Sifency EDD Theme Builder', 'sifency-addons' ),
				'icon'  => 'eicon-single-post',
			)
		);
	}

	/**
	 * Includes helper files (traits) required by the widgets.
	 */
	private function include_helper_files() {
		$helper_files = array(
			'includes/elementor/theme-builder/base/load.php',

			'includes/traits/help.php',
			'includes/traits/button.php',
			'includes/traits/master-toggle.php',
			'includes/traits/master-typography.php',
			'includes/traits/image.php',
			'includes/traits/icon.php',
			'includes/traits/item-style.php',
			'includes/traits/filter.php',
			'includes/traits/animation-controls.php',
			'includes/traits/parity-controls.php',
			'includes/traits/pagination.php',
			'includes/traits/post-arg-controls.php',
			'includes/traits/slider-navigation.php',
			'includes/traits/slider-pagination.php',
			'includes/traits/sifency_slider_controllers.php',
			'includes/traits/custom-css.php',
			'includes/traits/divider.php',
			'includes/traits/combine-button.php',
			'includes/traits/flex-align.php',
			'includes/traits/section-header.php',
			'includes/traits/combine-title.php',
			'includes/traits/layout.php',
			'includes/traits/Sifency_Addons_WooCommerce_Guard.php',
			'includes/traits/sticky-stack.php',
			'includes/traits/floating-count.php',

			'includes/traits/tb/themebuilder.php',
			'includes/traits/tb/render-contet-meta.php',
			'includes/traits/tb/label-content.php',
			'includes/traits/tb/separator-content.php',
			'includes/traits/tb/trio-text-style.php',
			'includes/traits/tb/the-title.php',

			'includes/elementor/extention/sticky/sticky.php',
			'includes/elementor/extention/animation/animation-extension.php',

			'includes/elementor/component/marquee/controls.php',
			'includes/elementor/component/button/controls.php',
			'includes/elementor/component/iconbox/controls.php',
			'includes/elementor/component/video/controls.php',
			'includes/elementor/component/image/controls.php',
			'includes/elementor/component/icon-list/controls.php',

			'includes/elementor/dynamic/author-box/controls.php',
			'includes/elementor/dynamic/comment/controls.php',
			'includes/elementor/dynamic/search/controls.php',
			'includes/elementor/master/controls/reels.php',

			'includes/elementor/post-type/post-navigator/controls.php',
			'includes/elementor/helpers/functions.php',
			'includes/elementor/loop/blog/controls.php',
			'includes/elementor/loop/awards/controls.php',
			'includes/elementor/loop/career/controls.php',
			'includes/elementor/loop/events/controls.php',
			'includes/elementor/loop/clients/controls.php',
			'includes/elementor/loop/stack/controls.php',
			'includes/elementor/loop/services/controls.php',
			'includes/elementor/loop/team/controls.php',
			'includes/elementor/loop/projects/controls.php',
			'includes/elementor/loop/testimonials/controls.php',

			'includes/elementor/plugins/form/controls.php',
			'includes/elementor/plugins/newsletter/controls.php',

			'includes/elementor/woocommerce/base/woo-base.php',
			'includes/elementor/woocommerce/base/style-controller.php',
			'includes/elementor/woocommerce/products-slider/controls.php',
			'includes/elementor/woocommerce/product-grid/controls.php',
			'includes/elementor/woocommerce/related-products/controls.php',
			'includes/elementor/woocommerce/product-image/controls.php',
			'includes/elementor/woocommerce/product-rating/controls.php',

			'includes/elementor/plugins/form/render.php',
			'includes/elementor/plugins/newsletter/render.php',
			'includes/elementor/plugins/template/render.php',
		);

		foreach ( $helper_files as $file ) {
			$file_path = SIFENCY_ADDONS_DIR . $file;
			if ( file_exists( $file_path ) ) {
				require_once $file_path;
			}
		}
	}

	/**
	 * Registers all enabled widgets with Elementor.
	 *
	 * It iterates through the flattened widget config, checks if a widget is enabled
	 * in the plugin settings, and then registers it.
	 *
	 * @param \Elementor\Widgets_Manager $widgets_manager The Elementor widgets manager.
	 */
	public function register_widgets( $widgets_manager ) {
		$this->include_helper_files();

		require_once SIFENCY_ADDONS_DIR . 'includes/elementor/atomic/class-sifency-atomic-environment.php';

		$enabled_widgets_settings = get_option( 'sifency_addons_settings', array() );
		$enabled_widgets          = $enabled_widgets_settings['widgets'] ?? array();
		$is_woo_active            = class_exists( 'WooCommerce' );
		$all_widgets              = Sifency_Addons_Widget_Registry::get_flat();

		foreach ( $all_widgets as $widget_id => $widget_data ) {
			if ( ! Sifency_Addons_Widget_Registry::should_register( $widget_id, $widget_data ) ) {
				continue;
			}
			$is_sync_state_widget = ! empty( $widget_data['sync_widget'] );
			if ( $is_sync_state_widget && ! class_exists( '\\Sifency_Addons_Theme_Builder_Master' ) ) {
				continue;
			}
			require_once SIFENCY_ADDONS_DIR . 'includes/elementor/helpers/sync-environment.php';
			require_once SIFENCY_ADDONS_DIR . 'includes/elementor/theme-builder/base/themebuilder-base.php';

			if ( $is_sync_state_widget && ! \Sifency_Addons_Theme_Builder_Master::sync_environment_state() ) {
				continue;
			}
			$is_widget_enabled = ! isset( $enabled_widgets[ $widget_id ] ) || 'on' === $enabled_widgets[ $widget_id ];

			if ( ! $is_widget_enabled ) {
				continue;
			}

			if ( ! empty( $widget_data['is_woo'] ) && ! $is_woo_active ) {
				continue;
			}

			if ( $this->try_register_atomic_widget( $widgets_manager, $widget_data, $widget_id ) ) {
				continue;
			}

			$file_path = SIFENCY_ADDONS_DIR . $widget_data['file'];
			if ( isset( $widget_data['full_path'] ) && $widget_data['full_path'] === true ) {
				$file_path = $widget_data['file'];
			} else {
				$file_path = SIFENCY_ADDONS_DIR . $widget_data['file'];
			}
			if ( ! file_exists( $file_path ) ) {
				continue;
			}

			require_once $file_path;

			$class_name = $widget_data['class'];
			if ( class_exists( $class_name ) ) {
				$widgets_manager->register( new $class_name() );
			}
		}
	}

	/**
	 * Loads Sifency atomic base classes (once) when Elementor atomic API is available.
	 */
	private function load_sifency_atomic_stack(): void {
		static $loaded = false;
		if ( $loaded ) {
			return;
		}
		if ( ! class_exists( '\Elementor\Modules\AtomicWidgets\Elements\Base\Atomic_Widget_Base' ) ) {
			return;
		}
		require_once SIFENCY_ADDONS_DIR . 'includes/elementor/atomic/class-sifency-atomic-widget-base.php';
		require_once SIFENCY_ADDONS_DIR . 'includes/elementor/atomic/trait-sifency-has-atomic-template.php';
		$loaded = true;
	}

	/**
	 * Registers the V4 atomic implementation when configured and the e_atomic_elements experiment is active.
	 *
	 * @param \Elementor\Widgets_Manager $widgets_manager Widgets manager.
	 * @param array                      $widget_data      Flat widget config entry.
	 * @param string                     $widget_id        Key in sifency-widgets.php (e.g. sifency-divider).
	 * @return bool True if atomic widget was registered (classic must be skipped).
	 */
	private function try_register_atomic_widget( $widgets_manager, array $widget_data, $widget_id ): bool {
		if ( empty( $widget_data['atomic_class'] ) || empty( $widget_data['atomic_file'] ) ) {
			return false;
		}
		if ( ! class_exists( '\Sifency_Atomic_Environment' ) ) {
			return false;
		}
		if ( ! \Sifency_Atomic_Environment::is_atomic_widgets_active() ) {
			return false;
		}
		if ( ! \Sifency_Atomic_Environment::is_elementor_meets_atomic_requirement() ) {
			return false;
		}

		$this->load_sifency_atomic_stack();
		if ( ! class_exists( '\Elementor\Modules\AtomicWidgets\Elements\Base\Atomic_Widget_Base' ) ) {
			return false;
		}

		$file_path = SIFENCY_ADDONS_DIR . $widget_data['atomic_file'];
		if ( ! file_exists( $file_path ) ) {
			return false;
		}

		require_once $file_path;

		$class_name = $widget_data['atomic_class'];
		if ( ! class_exists( $class_name ) ) {
			return false;
		}

		$widgets_manager->register( new $class_name() );

		/**
		 * Fires after a Sifency V4 atomic widget is registered (for QA, logging, or batching).
		 *
		 * @param string $class_name Registered widget class name.
		 * @param string $widget_id  Widget key from sifency-widgets.php (e.g. sifency-divider).
		 */
		do_action( 'sifency_addons_registered_atomic_widget', $class_name, $widget_id );

		return true;
	}
}
