<?php
/**
 * The file that defines the core plugin class
 *
 * @since      1.0.0
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 */

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

if ( ! class_exists( 'Captwiki_Widgets_Load' ) ) {

	/**
	 * It is Captain Widget Main Class
	 *
	 * @since 1.0.0
	 */
	class Captwiki_Widgets_Load {

		/**
		 * Member Variablec
		 *
		 * @var instance
		 */
		public static $instance;

		/**
		 * Member Variable
		 *
		 * @var widgets
		 */
		public $widgets;

		/**
		 * Member Variable
		 *
		 * @var woo_widgets
		 */
		public $woo_widgets;

		/**
		 * Initiator
		 *
		 * @since 1.0.0
		 */
		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Define the core functionality of the plugin.
		 *
		 * @since 1.0.0
		 */
		public function __construct() {

			$this->captwiki_get_widget_list();

			add_action( 'elementor/init', array( $this, 'captwiki_add_elementor_category' ) );
			add_action( 'elementor/editor/after_enqueue_scripts', array( $this, 'captwiki_editor_preview_js' ) );
			add_action( 'elementor/editor/after_enqueue_styles', array( $this, 'captwiki_register_styles_editor' ) );
			add_action( 'elementor/preview/enqueue_styles', array( $this, 'captwiki_enqueue_preview_styles' ) );

			$this->captwiki_widgets_registered();
			$this->captwiki_after_register_scripts();
		}

		/**
		 * Get widget list from options table
		 *
		 * @since 1.0.0
		 */
		public function captwiki_get_widget_list() {

			$captwiki_settings = get_option( 'captwiki_settings', array() );

			$this->widgets     = ! empty( $captwiki_settings['widgets'] ) && is_array( $captwiki_settings['widgets'] ) ? $captwiki_settings['widgets'] : array();
			$this->woo_widgets = ! empty( $captwiki_settings['woo_widgets'] ) && is_array( $captwiki_settings['woo_widgets'] ) ? $captwiki_settings['woo_widgets'] : array();
		}
		/**
		 * Add Elementor Category for Elements
		 *
		 * This method is responsible for adding a custom category to the Elementor Page Builder
		 * forelements.
		 *
		 * @since 1.0.0
		 */
		public function captwiki_add_elementor_category() {

			$elementor = \Elementor\Plugin::$instance;

			$captwiki_categories = array(
				'captwiki-essential'    => array(
					'title' => esc_html__( 'Captain Essential', 'captain-widgets-kit' ),
					'icon'  => 'fa fa-plug',
				),
				'captwiki-woo-commerce' => array(
					'title' => esc_html__( 'Captain WooCommerce', 'captain-widgets-kit' ),
					'icon'  => 'fa fa-plug',
				),
			);

			foreach ( $captwiki_categories as $index => $captwiki_widgets ) {
				$elementor->elements_manager->add_category(
					$index,
					array(
						'title' => $captwiki_widgets['title'],
						'icon'  => $captwiki_widgets['icon'],
					),
					1
				);
			}
		}

		/**
		 * Enqueue Editor Preview JS
		 *
		 * @since 1.1.0
		 */
		public function captwiki_editor_preview_js() {
			wp_enqueue_script( 'captwiki-editor-preview', CAPTWIKI_URL . '/assets/js/captwiki-editor-preview.js', array( 'jquery', 'elementor-editor' ), CAPTWIKI_VERSION, true );
		}

		/**
		 * Enqueue Editor Preview CSS
		 *
		 * @since 1.1.0
		 */
		public function captwiki_register_styles_editor() {
			wp_enqueue_style( 'captwiki-editor-preview-css', CAPTWIKI_URL . 'assets/css/captwiki-editor-preview.css', array( 'elementor-editor' ), CAPTWIKI_VERSION, false );
		}

		/**
		 * Add Elementor Category for Elements
		 *
		 * @since 1.0.0
		 */
		public function captwiki_widgets_registered() {

			add_action(
				'elementor/widgets/widgets_registered',
				function ( $widgets_manager ) {

					$this->captwiki_register_widgets( $widgets_manager );
				}
			);
		}

		/**
		 * Add Elementor Category for Elements
		 *
		 * @since 1.0.0
		 */
		public function captwiki_after_register_scripts() {

			add_action(
				'elementor/frontend/after_register_scripts',
				function () {
					$this->captwiki_register_widgets_script();
					$this->captwiki_register_widgets_style();
				}
			);
		}

		/**
		 * Check if widget is enabled.
		 *
		 * @since 1.0.0
		 *
		 * @param string $handle The widget handle to check.
		 * @return bool True if enabled, false otherwise.
		 */
		public function captwiki_is_widget_enabled( $handle ) {

			return $this->captwiki_is_enabled( $handle, $this->widgets );
		}

		/**
		 * Check if WooCommerce widget is enabled.
		 *
		 * @since 1.0.0
		 *
		 * @param string $handle The widget handle to check.
		 * @return bool True if enabled, false otherwise.
		 */
		public function captwiki_is_woo_widget_enabled( $handle ) {

			return $this->captwiki_is_enabled( $handle, $this->woo_widgets );
		}

		/**
		 * Check if a saved setting contains a widget handle.
		 *
		 * @since 1.0.0
		 *
		 * @param string $handle  The widget handle to check.
		 * @param array  $enabled Enabled widget handles.
		 * @return bool
		 */
		private function captwiki_is_enabled( $handle, $enabled ) {

			if ( empty( $enabled ) || ! is_array( $enabled ) ) {
				return false;
			}

			$aliases = array(
				'captwiki-blog-card'          => 'captwiki-blog-grid',
				'captwiki-gallery-listing'    => 'captwiki-gallery-listing',
				'captwiki-hotspot'            => 'captwiki-image-hotspot',
				'captwiki-process-steps'      => 'captwiki-process-steps',
				'captwiki-promo-bar'          => 'captwiki-sticky-promo-bar',
				'captwiki-scroll-navigation'  => 'captwiki-scroll-navigation-dots',
				'captwiki-social-icon'        => 'captwiki-social-icons',
				'captwiki-tabs-tour'          => 'captwiki-tabs',
				'captwiki-testimonial'        => 'advanced-testimonial-carousel',
				'captwiki-woo-breadcrumb'     => 'captwiki-woo-breadcrumb',
				'captwiki-woo-compare'        => 'captwiki-compare-table-pro',
				'captwiki-woo-description'    => 'captwiki-product-description',
				'captwiki-woo-product-expert' => 'captwiki-product-excerpt-advanced',
				'captwiki-woo-product-meta'   => 'captwiki-product-meta',
				'captwiki-woo-product-notice' => 'captwiki-woo-product-notice',
				'captwiki-woo-product-rating' => 'captwiki-product-rating',
				'captwiki-woo-product-tab'    => 'captwiki-woo-product-tab',
				'captwiki-woo-mini-cart'      => 'captwiki-woo-mini-cart-popup',
				'captwiki-woo-product-tabs'   => 'captwiki-woo-product-tab',
				'captwiki-woo-sales-bsadge'   => 'captwiki-woo-sales-badge',
			);

			$normalized_enabled = array_map( array( $this, 'captwiki_normalize_handle' ), $enabled );
			$normalized_handle  = $this->captwiki_normalize_handle( $handle );
			$normalized_alias   = isset( $aliases[ $normalized_handle ] ) ? $this->captwiki_normalize_handle( $aliases[ $normalized_handle ] ) : $normalized_handle;

			return in_array( $normalized_handle, $normalized_enabled, true ) || in_array( $normalized_alias, $normalized_enabled, true );
		}

		/**
		 * Normalize widget handles for settings comparison.
		 *
		 * @since 1.0.0
		 *
		 * @param string $handle The widget handle.
		 * @return string
		 */
		private function captwiki_normalize_handle( $handle ) {

			$handle        = strtolower( str_replace( '_', '-', (string) $handle ) );
			$legacy_prefix = implode( '', array( 'cra', 'ft-' ) );

			if ( 0 === strpos( $handle, $legacy_prefix ) ) {
				$handle = 'captwiki-' . substr( $handle, strlen( $legacy_prefix ) );
			}

			return $handle;
		}

		/**
		 * Register custom widgets with the widgets manager.
		 *
		 * @since 1.0.0
		 *
		 * @param \Elementor\Widgets_Manager $widgets_manager Elementor widgets manager instance.
		 * @return void
		 */
		public function captwiki_register_widgets( $widgets_manager ) {

			$widgets = array(
				'captwiki-button'        => array( 'button', 'Captwiki_Button' ),
				'captwiki-dual-button'   => array( 'dual-button', 'Captwiki_Dual_Button' ),
				'captwiki-post-author'   => array( 'post-author', 'Captwiki_Post_Author' ),
				'captwiki-post-comments' => array( 'post-comments', 'Captwiki_Post_Comments' ),
				'captwiki-post-content'  => array( 'post-content', 'Captwiki_Post_Content' ),
				'captwiki-post-title'    => array( 'post-title', 'Captwiki_Post_Title' ),
				'captwiki-heading-title' => array( 'heading-title', 'Captwiki_Heading_Title' ),
				'captwiki-star-rating'   => array( 'star-rating', 'Captwiki_Star_Rating' ),
				'captwiki-blockquote'    => array( 'blockquote', 'Captwiki_Blockquote' ),
				'captwiki-countdown'     => array( 'countdown', 'Captwiki_Countdown' ),
				'captwiki-pricing'       => array( 'pricing-box', 'Captwiki_Pricing_Box' ),
				'captwiki-testimonial'   => array( 'testimonial', 'Captwiki_Testimonial' ),
				'captwiki-tabs'          => array( 'tabs', 'Captwiki_Tabs' ),
				'captwiki-separator'     => array( 'separator', 'Captwiki_Separator' ),
				'captwiki-site-logo'     => array( 'site-logo', 'Captwiki_Site_Logo' ),
				'captwiki-text-block'    => array( 'text-block', 'Captwiki_Text_Block' ),
				'captwiki-social-icons'  => array( 'social-icon', 'Captwiki_Social_Icon' ),
				'captwiki-grid-listing'   => array( 'grid-listing', 'Captwiki_Grid_Listing' ),
				'captwiki-search-filter'  => array( 'search-filter', 'Captwiki_Search_Filter' ),
				'captwiki-search-bar'     => array( 'search-bar', 'Captwiki_Search_Bar' ),
				'captwiki-table'          => array( 'table', 'Captwiki_Table' ),
				'captwiki-gallery-listing' => array( 'gallery-listing', 'Captwiki_Gallery_Listing' ),
				'captwiki-age-gate'       => array( 'age-gate', 'Captwiki_Age_Gate' ),
				'captwiki-cookie-consent' => array( 'cookie-consent', 'Captwiki_Cookie_Consent' ),
				'captwiki-animated-box'   => array( 'animated-box', 'Captwiki_Animated_Box' ),
				'captwiki-animated-marquee' => array( 'animated-marquee', 'Captwiki_Animated_Marquee' ),
				'captwiki-mega-menu'      => array( 'mega-menu', 'Captwiki_Mega_Menu' ),
				'captwiki-scroll-navigation-dots' => array( 'scroll-navigation-dots', 'Captwiki_Scroll_Navigation_Dots' ),
				'captwiki-progress-bar'   => array( 'progress-bar', 'Captwiki_Progress_Bar' ),
				'captwiki-side-menu'      => array( 'side-menu', 'Captwiki_Side_Menu' ),
			);

			foreach ( $widgets as $widget_id => $widget ) {
				list( $file_name, $class_name ) = $widget;

				$path = CAPTWIKI_PATH . 'includes/elementor/widgets/class-captwiki-' . sanitize_file_name( $file_name ) . '.php';

				if ( file_exists( $path ) && $this->captwiki_is_widget_enabled( $widget_id ) ) {
					require_once $path;
					$widgets_manager->register( new $class_name() );
				}
			}
		}

		/**
		 * Register Woo Widgets
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public function captwiki_register_widgets_script() {

			$captwiki_scripts = array(
				'captwiki-button'         => array( 'button/captwiki-button.js', true ),
				'captwiki-site-logo'      => array( 'site-logo/captwiki-site-logo.js', true ),
				'captwiki-grid-listing'   => array( 'grid-listing/captwiki-grid-listing.js', true ),
				'captwiki-search-filter'  => array( 'search-filter/captwiki-search-filter.js', true ),
				'captwiki-search-bar'     => array( 'search-bar/captwiki-search-bar.js', true ),
				'captwiki-countdown'      => array( 'countdown/captwiki-countdown.js', true ),
				'captwiki-testimonial'    => array( 'testimonial/captwiki-testimonial.js', true ),
				'captwiki-tabs'           => array( 'tabs/captwiki-tabs.js', true ),
				'captwiki-table'          => array( 'table/captwiki-table.js', true ),
				'captwiki-gallery-listing' => array( 'gallery-listing/captwiki-gallery-listing.js', true ),
				'captwiki-age-gate'       => array( 'age-gate/captwiki-age-gate.js', true ),
				'captwiki-cookie-consent' => array( 'cookie-consent/captwiki-cookie-consent.js', true ),
				'captwiki-animated-box'   => array( 'animated-box/captwiki-animated-box.js', true ),
				'captwiki-mega-menu'      => array( 'mega-menu/captwiki-mega-menu.js', true ),
				'captwiki-scroll-navigation-dots' => array( 'scroll-navigation-dots/captwiki-scroll-navigation-dots.js', true ),
				'captwiki-progress-bar'   => array( 'progress-bar/captwiki-progress-bar.js', true ),
				'captwiki-side-menu'      => array( 'side-menu/captwiki-side-menu.js', true ),
			);

			foreach ( $captwiki_scripts as $handle => [$src, $in_footer] ) {
				if ( $this->captwiki_is_widget_enabled( $handle ) ) {
					wp_enqueue_script( $handle, esc_url( CAPTWIKI_URL . 'assets/js/widgets/' . $src ), array(), CAPTWIKI_VERSION, $in_footer );
				}
			}
		}

		/**
		 * Register Woo Widgets
		 *
		 * @since 1.0.0
		 * @version 1.1.0
		 *
		 * @return void
		 */
		public function captwiki_register_widgets_style() {

			$styles = array(
				'captwiki_button'        => 'button/captwiki-button.css',
				'captwiki_dual_button'   => 'dual-button/captwiki-dual-button.css',
				'captwiki_post_author'   => 'post-author/captwiki-post-author.css',
				'captwiki_post_comments' => 'post-comments/captwiki-post-comments.css',
				'captwiki_post_content'  => 'post-content/captwiki-post-content.css',
				'captwiki_post_title'    => 'post-title/captwiki-post-title.css',
				'captwiki_heading_title' => 'heading-title/captwiki-heading-title.css',
				'captwiki_star_rating'   => 'star-rating/captwiki-star-rating.css',
				'captwiki_blockquote'    => 'blockquote/captwiki-blockquote.css',
				'captwiki_countdown'     => 'countdown/captwiki-countdown.css',
				'captwiki_pricing'       => 'pricing/captwiki-pricing.css',
				'captwiki_testimonial'   => 'testimonial/captwiki-testimonial.css',
				'captwiki_tabs'          => 'tabs/captwiki-tabs.css',
				'captwiki_separator'     => 'separator/captwiki-separator.css',
				'captwiki_site_logo'     => 'site-logo/captwiki-site-logo.css',
				'captwiki_text_block'    => 'text-block/captwiki-text-block.css',
				'captwiki_social_icon'   => 'social-icon/social-icon.css',
				'captwiki_grid_listing'   => 'listing/captwiki-grid-listing.css',
				'captwiki_search_filter'  => 'search-filter/captwiki-search-filter.css',
				'captwiki_search_bar'     => 'search-bar/captwiki-search-bar.css',
				'captwiki_table'          => 'table/captwiki-table.css',
				'captwiki_gallery_listing' => 'gallery-listing/captwiki-gallery-listing.css',
				'captwiki_age_gate'       => 'age-gate/captwiki-age-gate.css',
				'captwiki_cookie_consent' => 'cookie-consent/captwiki-cookie-consent.css',
				'captwiki_animated_box'   => 'animated-box/captwiki-animated-box.css',
				'captwiki_animated_marquee' => 'animated-marquee/captwiki-animated-marquee.css',
				'captwiki_mega_menu'      => 'mega-menu/captwiki-mega-menu.css',
				'captwiki_scroll_navigation_dots' => 'scroll-navigation-dots/captwiki-scroll-navigation-dots.css',
				'captwiki_progress_bar'   => 'progress-bar/captwiki-progress-bar.css',
				'captwiki_side_menu'      => 'side-menu/captwiki-side-menu.css',
			);

			foreach ( $styles as $handle => $src ) {

				if ( $this->captwiki_is_widget_enabled( $handle ) ) {

					if ( 'captwiki_grid_listing' === $handle ) {
						wp_enqueue_style( 'captwiki-listing-col-css', esc_url( CAPTWIKI_URL . 'assets/css/global/listing/captwiki-listing-col.css' ), array(), CAPTWIKI_VERSION );
					}

					wp_enqueue_style( $handle, esc_url( CAPTWIKI_URL . 'assets/css/widgets/' . $src ), array(), CAPTWIKI_VERSION );
				}
			}
		}

		/**
		 * Multi-style widgets map.
		 *
		 * Jin widgets me selectable styles hain, unka common handle + style file
		 * prefix + available styles yahan list hote hain. Editor preview me saari
		 * style files load karne ke liye use hota hai.
		 *
		 * @since 1.3.0
		 * @return array
		 */
		private function captwiki_multi_style_widgets() {

			return array(
				'captwiki-heading-title' => array(
					'common' => 'heading-title/captwiki-heading-title.css',
					'prefix' => 'heading-title/captwiki-heading-title',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5', 'style-6' ),
				),
				'captwiki-star-rating'   => array(
					'common' => 'star-rating/captwiki-star-rating.css',
					'prefix' => 'star-rating/captwiki-star-rating',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-blockquote'    => array(
					'common' => 'blockquote/captwiki-blockquote.css',
					'prefix' => 'blockquote/captwiki-blockquote',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-countdown'     => array(
					'common' => 'countdown/captwiki-countdown.css',
					'prefix' => 'countdown/captwiki-countdown',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-pricing'       => array(
					'common' => 'pricing/captwiki-pricing.css',
					'prefix' => 'pricing/captwiki-pricing',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-testimonial'   => array(
					'common' => 'testimonial/captwiki-testimonial.css',
					'prefix' => 'testimonial/captwiki-testimonial',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-tabs'          => array(
					'common' => 'tabs/captwiki-tabs.css',
					'prefix' => 'tabs/captwiki-tabs',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-table'         => array(
					'common' => 'table/captwiki-table.css',
					'prefix' => 'table/captwiki-table',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-gallery-listing' => array(
					'common' => 'gallery-listing/captwiki-gallery-listing.css',
					'prefix' => 'gallery-listing/captwiki-gallery-listing',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-age-gate'      => array(
					'common' => 'age-gate/captwiki-age-gate.css',
					'prefix' => 'age-gate/captwiki-age-gate',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-cookie-consent' => array(
					'common' => 'cookie-consent/captwiki-cookie-consent.css',
					'prefix' => 'cookie-consent/captwiki-cookie-consent',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-animated-box'  => array(
					'common' => 'animated-box/captwiki-animated-box.css',
					'prefix' => 'animated-box/captwiki-animated-box',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-animated-marquee' => array(
					'common' => 'animated-marquee/captwiki-animated-marquee.css',
					'prefix' => 'animated-marquee/captwiki-animated-marquee',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-mega-menu'     => array(
					'common' => 'mega-menu/captwiki-mega-menu.css',
					'prefix' => 'mega-menu/captwiki-mega-menu',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-scroll-navigation-dots' => array(
					'common' => 'scroll-navigation-dots/captwiki-scroll-navigation-dots.css',
					'prefix' => 'scroll-navigation-dots/captwiki-scroll-navigation-dots',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-progress-bar'  => array(
					'common' => 'progress-bar/captwiki-progress-bar.css',
					'prefix' => 'progress-bar/captwiki-progress-bar',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
				'captwiki-side-menu'     => array(
					'common' => 'side-menu/captwiki-side-menu.css',
					'prefix' => 'side-menu/captwiki-side-menu',
					'styles' => array( 'style-1', 'style-2', 'style-3', 'style-4', 'style-5' ),
				),
			);
		}

		/**
		 * Enqueue every style variant inside the Elementor editor preview.
		 *
		 * Frontend par render() sirf active style load karta hai. Editor me widget
		 * AJAX se re-render hota hai isliye late wp_enqueue_style preview iframe me
		 * inject nahi hoti — yahan saari styles pehle se load kar dete hain taaki
		 * style switch turant dikhe.
		 *
		 * @since 1.3.0
		 * @return void
		 */
		public function captwiki_enqueue_preview_styles() {

			foreach ( $this->captwiki_multi_style_widgets() as $widget_id => $data ) {

				if ( ! $this->captwiki_is_widget_enabled( $widget_id ) ) {
					continue;
				}

				$common_handle = str_replace( '-', '_', $widget_id );

				wp_enqueue_style( $common_handle, esc_url( CAPTWIKI_URL . 'assets/css/widgets/' . $data['common'] ), array(), CAPTWIKI_VERSION );

				foreach ( $data['styles'] as $style ) {
					wp_enqueue_style(
						$widget_id . '-' . $style,
						esc_url( CAPTWIKI_URL . 'assets/css/widgets/' . $data['prefix'] . '-' . $style . '.css' ),
						array( $common_handle ),
						CAPTWIKI_VERSION
					);
				}
			}
		}
	}

	Captwiki_Widgets_Load::get_instance();
}
