<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Plugin as ElementorPlugin;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Css_Filter;
use Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Product_image_Controls;

class Sifency_Widget_Product_Image extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Product_image_Controls;

	public function get_name() {
		return 'sifency-product-image';
	}

	public function get_title() {
		return esc_html__( 'Sifency Product Image', 'sifency-addons' );
	}

	public function get_icon() {
		return 'eicon-product-images';
	}

	public function get_categories() {
		return [ 'sifency-addons-woo-widgets' ];
	}

	public function get_keywords() {
		return [ 'product', 'image', 'gallery', 'thumbnail', 'woocommerce', 'sifency' ];
	}

	protected function register_controls() {
		$this->add_sifency_product_image_controls();
		$this->add_sifency_animation_controls();
        $this->update_control(
            'sifency_animation_target',
            [
                'type' => Controls_Manager::HIDDEN,
                'default' => 'wrapper',
            ]
        );
	}

    protected function render() {

        if ( ! class_exists('woocommerce') ) {
            if ( ElementorPlugin::$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 ( ElementorPlugin::$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 ( ElementorPlugin::$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_Animation_Manager($settings);
        $wrapper_classes = ['sifency-product-image-wrapper'];
        $wrapper_attrs = $animation_manager->get_wrapper_attributes($wrapper_classes);
		?>
		<div <?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 = [
            'post_type'      => 'product',
            'posts_per_page' => 1,
            'post_status'    => 'publish',
            'orderby'        => 'date',
            'order'          => 'DESC',
            'meta_query'     => [
                'relation' => 'OR',
                [
                    'key'     => '_sale_price',
                    'value'   => 0,
                    'compare' => '>',
                    'type'    => 'numeric'
                ],
                [
                    '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(['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;
    }
}