<?php
/**
 * Elementor integration for Product Display
 *
 * @package Product_Display
 */

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

/**
 * Class PRODDISP_Elementor
 *
 * This class handles the Elementor integration for Product Display plugin.
 */
class PRODDISP_Elementor {
	/**
	 * The single instance of the class
	 */
	protected static $_instance = null;

	/**
	 * Main Instance
	 */
	public static function get_instance() {
		if ( is_null(self::$_instance) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Constructor
	 */
	public function __construct() {
		// Use the correct hooks for different Elementor versions
		add_action('elementor/widgets/widgets_registered', array( $this, 'register_widgets' ));
		add_action('elementor/widgets/register', array( $this, 'register_widgets_new' ));
		add_action('elementor/elements/categories_registered', array( $this, 'register_category' ));
		add_action('elementor/editor/after_enqueue_scripts', array( $this, 'enqueue_editor_scripts' ));
		add_action('elementor/preview/enqueue_styles', array( $this, 'enqueue_preview_assets' ));
		add_action('wp_ajax_proddisp_get_showcase_info', array( $this, 'ajax_get_showcase_info' ));
		add_action('elementor/controls/register', array( $this, 'register_icon_picker_control' ));
	}

	/**
	 * Register Elementor category
	 */
	public function register_category( $elements_manager ) {
		$elements_manager->add_category(
			'product-display',
			array(
				'title' => __('Product Display', 'product-display'),
				'icon' => 'fa fa-shopping-cart',
			)
		);
	}

	/**
	 * Register widgets (for older Elementor versions)
	 */
	public function register_widgets() {
		$this->register_widget_instance();
	}

	/**
	 * Register widgets (for newer Elementor versions)
	 */
	public function register_widgets_new( $widgets_manager ) {
		$this->register_widget_instance($widgets_manager);
	}

	/**
	 * Common method to register widget instance
	 */
	private function register_widget_instance( $widgets_manager = null ) {
		// Check if Elementor is loaded
		if ( ! did_action('elementor/loaded') ) {
			return;
		}

		$widget_file = PRODDISP_PLUGIN_DIR . 'inc/elementor/class-proddisp-elementor-widget.php';

		if ( ! file_exists($widget_file) ) {
			return;
		}

		require_once $widget_file;

		// Check if class exists before registering
		if ( class_exists('PRODDISP_Elementor_Widget') ) {
			$widget_instance = new PRODDISP_Elementor_Widget();

			// Use the provided widgets manager or get the default one
			$manager = $widgets_manager ?: \Elementor\Plugin::instance()->widgets_manager;

			// Try both registration methods for compatibility
			if ( method_exists($manager, 'register') ) {
				$manager->register($widget_instance);
			} elseif ( method_exists($manager, 'register_widget_type') ) {
				$manager->register_widget_type($widget_instance);
			}
		}
	}

	/**
	 * Register custom icon picker control for Elementor
	 */
	public function register_icon_picker_control( $controls_manager ) {
		require_once PRODDISP_PLUGIN_DIR . 'inc/elementor/class-proddisp-icon-picker-control.php';

		if ( class_exists('PRODDISP_Icon_Picker_Control') ) {
			$control_instance = new PRODDISP_Icon_Picker_Control();

			// Try both registration methods for compatibility
			if ( method_exists($controls_manager, 'register') ) {
				$controls_manager->register($control_instance);
			} elseif ( method_exists($controls_manager, 'register_control') ) {
				$controls_manager->register_control($control_instance->get_type(), $control_instance);
			}
		}
	}

	/**
	 * Enqueue editor scripts
	 */
	public function enqueue_editor_scripts() {
		$js_file = PRODDISP_PLUGIN_DIR . 'assets/build/js/wcps-elementor-widget.min.js';

		// Only enqueue if file exists
		if ( file_exists($js_file) ) {
			wp_enqueue_script(
				'proddisp-elementor-editor',
				PRODDISP_PLUGIN_URL . 'assets/build/js/wcps-elementor-widget.min.js',
				array( 'jquery' ),
				PRODDISP_VERSION,
				true
			);

			wp_localize_script('proddisp-elementor-editor', 'proddisp_elementor', array(
				'nonce' => wp_create_nonce('proddisp_elementor_nonce'),
				'fontAwesome' => array(
					'version' => '6.4.0',
					'loaded' => true,
					'icons' => PRODDISP_Assets::get_instance()->get_fontawesome_icons_public(),
				),
			));
		} else {
			if ( defined('WP_DEBUG') && WP_DEBUG ) {
				error_log('Product Display: Elementor widget JS file not found: ' . $js_file);
			}
		}

		// Enqueue FontAwesome for Elementor editor
		wp_enqueue_style('wcps-font-awesome');

		// Add custom CSS for icon previews in Elementor
		wp_add_inline_style('wcps-font-awesome', '
			.proddisp-icon-preview {
				background: #f8f9fa;
				padding: 10px;
				border-radius: 4px;
				margin-top: 8px;
				border-left: 3px solid #71d7f7;
			}
			.proddisp-icon-preview strong {
				display: block;
				margin-bottom: 6px;
				color: #495157;
				font-size: 11px;
				text-transform: uppercase;
				letter-spacing: 0.5px;
			}
			.proddisp-icon-preview .icon-display {
				display: flex;
				align-items: center;
				gap: 8px;
				color: #71d7f7;
				font-weight: 500;
			}
			.proddisp-icon-preview .icon-display i {
				font-size: 16px;
				width: 20px;
				text-align: center;
			}
		');

		// Add JavaScript for icon preview updates
		wp_add_inline_script('proddisp-elementor-editor', '
			jQuery(document).ready(function($) {
				// Update icon previews when select values change
				function updateIconPreview(controlName, iconClass) {
					var $preview = $(".proddisp-icon-preview[data-icon-control=\"" + controlName + "\"] .icon-display");
					if ($preview.length && iconClass) {
						$preview.html("<i class=\"" + iconClass + "\"></i> " + iconClass);
					}
				}

				// Listen for control changes
				$(document).on("change", "[data-setting]", function() {
					var controlName = $(this).data("setting");
					var iconClass = $(this).val();
					
					if (controlName && controlName.indexOf("_icon") !== -1) {
						updateIconPreview(controlName, iconClass);
					}
				});
			});
		');
	}

	/**
	 * Enqueue preview assets for Elementor editor
	 */
	public function enqueue_preview_assets() {
		// Enqueue all necessary assets for Elementor preview
		PRODDISP_Assets::get_instance()->enqueue_frontend_assets();
		PRODDISP_Assets::get_instance()->enqueue_feature_assets();
		PRODDISP_Assets::get_instance()->enqueue_slider_assets();
		PRODDISP_Assets::get_instance()->enqueue_masonry_assets();

		// Enqueue wishlist assets
		if ( class_exists('PRODDISP_Wishlist') ) {
			PRODDISP_Wishlist::get_instance()->enqueue_scripts();
		}

		// Enqueue PRO assets if available
		if ( PRODDISP_Loader::is_pro_active() && class_exists('PRODDISP_PRO_Assets') ) {
			PRODDISP_PRO_Assets::get_instance()->enqueue_frontend_assets();
		}
	}

	/**
	 * AJAX handler to get showcase information
	 */
	public function ajax_get_showcase_info() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_elementor_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Check user capabilities
		if ( ! current_user_can('edit_posts') ) {
			wp_send_json_error('Insufficient permissions');
		}

		$showcase_id = isset($_POST['showcase_id']) ? sanitize_text_field( wp_unslash( $_POST['showcase_id']) ) : '';

		if ( empty($showcase_id) ) {
			wp_send_json_error('No showcase ID provided');
		}

		// Get showcase data
		$showcases = get_option('proddisp_saved_showcases', array());

		if ( ! isset($showcases[ $showcase_id ]) ) {
			wp_send_json_error('Showcase not found');
		}

		$showcase = $showcases[ $showcase_id ];

		// Prepare response data
		$response_data = array(
			'layout' => isset($showcase['layout']) ? ucfirst($showcase['layout']) : 'Grid',
			'mode' => isset($showcase['proddisp_layout_mode']) ? ucfirst(str_replace('-', ' ', $showcase['proddisp_layout_mode'])) : '',
			'columns' => isset($showcase['columns']) ? $showcase['columns'] : '4',
			'product_count' => isset($showcase['limit']) ? $showcase['limit'] : '4',
		);

		wp_send_json_success($response_data);
	}
}
