<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Sifency\Classes\Sifency_Addons_Widget_Base;
use Sifency\Classes\Sifency_Themebuilder_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Plugin;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Product_image_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;
use Sifency\Traits\Sifency_Addons_WooCommerce_Guard;
class Sifency_Widget_Product_Image extends Sifency_Themebuilder_Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Product_image_Controls;
	use Sifency_Addons_Help_Controls;
	use Sifency_Addons_WooCommerce_Guard;

	protected function get_allowed_template_types() {
		return 'product';
	}
	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'          => 'sifency-product-image',
			'title'         => 'Sifency Product Image',
			'icon'          => 'eicon-product-images',
			'category'      => 'sifency-addons-woo-widgets',
			'style_depends' => array( 'sifency-typo-style' ),
			'keywords'      => array( 'product', 'image', 'gallery', 'thumbnail', 'woocommerce', 'sifency' ),
		);
	}

	protected function register_controls() {
		if ( ! $this->check_and_guard_woocommerce() ) {
			return;
		}
		$this->add_sifency_product_image_controls();
		$this->add_sifency_addons_help_controls();
		$this->add_Sifency_Addons_Animation_Controls();
		$this->update_control(
			'sifency_animation_target',
			array(
				'type'    => Controls_Manager::HIDDEN,
				'default' => 'wrapper',
			)
		);
	}

	protected function render_dom( array $context ) {
		$wrapper_id = esc_attr( $context['dom_id'] );

		if ( ! class_exists( 'woocommerce' ) ) {
			if ( Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="sifency-placeholder">' . esc_html__( 'WooCommerce is not active.', 'sifency-addons' ) . '</div>';
			}
			return;
		}

		$product = null;
		// Accessing the global $product object from WooCommerce.
		global $product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

		if ( Plugin::$instance->editor->is_edit_mode() && ! $product instanceof \WC_Product ) {
			$product = $this->_get_preview_product(); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
		}

		if ( ! $product instanceof \WC_Product ) {
			if ( Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="sifency-placeholder">' . esc_html__( 'Product Image will be displayed here. Make sure you are on a single product page or have products in your store for the preview.', 'sifency-addons' ) . '</div>';
			}
			return;
		}

		// Accessing the global $product object from WooCommerce.
		$GLOBALS['product'] = $product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

		$settings = $this->get_settings_for_display();

		$show_sale_flash = isset( $settings['show_sale_flash'] ) ? $settings['show_sale_flash'] : 'yes';

		if ( 'yes' !== $show_sale_flash ) {
			add_filter( 'woocommerce_sale_flash', '__return_false' );
		}

		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );
		$wrapper_classes   = array( 'sifency-product-image-wrapper' );
		$wrapper_attrs     = $animation_manager->get_wrapper_attributes( $wrapper_classes );
		?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>" <?php echo wp_kses_post( $wrapper_attrs ); ?>>
			<?php woocommerce_show_product_images(); ?>
		</div>
		<?php

		if ( 'yes' !== $show_sale_flash ) {
			remove_filter( 'woocommerce_sale_flash', '__return_false' );
		}
	}

	/**
	 * Get a sample product for preview in Elementor editor if no product context is found.
	 *
	 * @return WC_Product|false A WC_Product object or false if no product is found.
	 */
	private function _get_preview_product() {
		if ( ! class_exists( 'woocommerce' ) ) {
			return false;
		}
		$args = array(
			'post_type'      => 'product',
			'posts_per_page' => 1,
			'post_status'    => 'publish',
			'orderby'        => 'date',
			'order'          => 'DESC',
			'meta_query'     => array(
				'relation' => 'OR',
				array(
					'key'     => '_sale_price',
					'value'   => 0,
					'compare' => '>',
					'type'    => 'numeric',
				),
				array(
					'key'     => '_product_image_gallery',
					'value'   => '',
					'compare' => '!=',
				),
			),
		);

		$query = new \WP_Query( $args );

		if ( $query->have_posts() ) {
			$query->the_post();
			$product_id = get_the_ID();
			wp_reset_postdata();
			return wc_get_product( $product_id );
		}

		$fallback_query = new \WP_Query(
			array(
				'post_type'      => 'product',
				'posts_per_page' => 1,
				'post_status'    => 'publish',
			)
		);
		if ( $fallback_query->have_posts() ) {
			$fallback_query->the_post();
			$product_id = get_the_ID();
			wp_reset_postdata();
			return wc_get_product( $product_id );
		}

		return false;
	}
}
