<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Plugin as ElementorPlugin;
use Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Related_Product_Controls;

class Sifency_Widget_Related_Products extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Addons_Slider_Controls;
    use Sifency_Related_Product_Controls;

	public function get_name() {
		return 'sifency-related-products';
	}

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

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

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

	public function get_keywords() {
		return [ 'product', 'related', 'upsell', 'cross-sell', 'woocommerce', 'sifency' ];
	}

    public function get_script_depends() {
        return $this->get_carousel_script_depends();
    }

    public function get_style_depends() {
        return $this->get_carousel_style_depends();
    }

	protected function register_controls() {
        $this->add_sifency_related_product_controls();
        $this->add_sifency_animation_controls();
	}

    protected function render() {
        // --- WooCommerce Check ---
        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;
        }
        // Accessing the global $product object from WooCommerce.
        global $product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
        $original_product = $product;
        $settings = $this->get_settings_for_display();

        // Use current product context or fallback
        $product = wc_get_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 context not found. Please view this on a single product page or ensure you have products for preview.', 'sifency-addons') . '</div>';
            }
            return;
        }

        // --- Query Related Products ---
        $this->animation_manager_instance = new Sifency_Animation_Manager($settings);

        $product_ids = [];
        switch ($settings['related_by']) {
            case 'upsell_ids':
                $product_ids = $product->get_upsell_ids();
                break;
            case 'cross_sell_ids':
                $product_ids = $product->get_cross_sell_ids();
                break;
            case 'related_ids':
                 $product_ids = wc_get_related_products($product->get_id(), $settings['posts_per_page'], $product->get_upsell_ids());
                 break;
        }

        $args = [
            'post_type'      => 'product',
            'posts_per_page' => (int) $settings['posts_per_page'],
            'orderby'        => $settings['orderby'],
            'order'          => $settings['order'],
            'post__in'       => $product_ids,
            'post__not_in'   => [ $product->get_id() ],
        ];

        // Fallback by taxonomy
        if ( empty($product_ids) && in_array($settings['related_by'], ['category', 'product_tag', 'related_ids'], true) ) {
            unset($args['post__in']);

            $taxonomy = ('related_ids' === $settings['related_by']) ? 'category' : $settings['related_by'];

            $term_ids = wc_get_product_term_ids($product->get_id(), $taxonomy);
            if ( ! empty($term_ids) ) {
                $args['tax_query'][] = [
                    'taxonomy' => $taxonomy,
                    'field'    => 'term_id',
                    'terms'    => $term_ids,
                ];
            }
        }

        if ($settings['related_by'] !== 'upsell_ids') {
            $upsell_ids = $product->get_upsell_ids();
            if (!empty($upsell_ids)) {
                $args['post__not_in'] = array_merge($args['post__not_in'], $upsell_ids);
            }
        }

        $related_query = new \WP_Query($args);

        if ( ! $related_query->have_posts() ) {
            if ( ElementorPlugin::$instance->editor->is_edit_mode() ) {
                echo '<div class="sifency-placeholder">' . esc_html__('No related products found for the current selection.', 'sifency-addons') . '</div>';
            }
            return;
        }

        // --- Wrapper Attributes ---
        $wrapper_classes = ['sifency-related-products-wrapper'];
        $wrapper_attrs_string = $this->animation_manager_instance->get_wrapper_attributes($wrapper_classes, false);

        $is_carousel = ('carousel' === $settings['layout_style']);
        $this->add_render_attribute('wrapper', 'class', $wrapper_classes);

        if ( $is_carousel ) {
            $slider_options = $this->get_sifency_swiper_options($settings, $related_query->post_count);
            $this->add_render_attribute('wrapper', 'class', 'sifency-carousel-wrapper');
            $this->add_render_attribute('wrapper', 'data-swiper-options', wp_json_encode($slider_options));
        }

        // --- Child Animation Support ---
        if ( 'child' === ($settings['sifency_animation_target'] ?? 'wrapper') ) {
            add_filter('woocommerce_post_class', [ $this, '_filter_product_class' ], 10, 2);
        }
        ?>
        <div <?php echo wp_kses_post( $this->get_render_attribute_string( 'wrapper' ) . ' ' . $wrapper_attrs_string ); ?>>
            <section class="related products">

                <?php if ( 'yes' === $settings['show_heading'] && ! empty($settings['heading_text']) ) :
                    $heading_tag = $settings['heading_tag'];
                    printf('<%1$s>%2$s</%1$s>', tag_escape($heading_tag), esc_html($settings['heading_text']));
                endif; ?>

                <?php if ( $is_carousel ) : ?>
                    <div class="swiper" data-swiper-options='<?php echo wp_json_encode($slider_options); ?>'>
                        <div class="swiper-wrapper products">
                            <?php
                            while ( $related_query->have_posts() ) :
                                $related_query->the_post();
                                $this->add_render_attribute('slide', 'class', 'swiper-slide product', true);
                                $slide_attrs = $this->animation_manager_instance->get_item_attributes([]);
                                if ( is_array($slide_attrs) ) {
                                    foreach ( $slide_attrs as $key => $value ) {
                                        $this->add_render_attribute('slide', $key, $value);
                                    }
                                }
                                ?>
                                <div <?php  ?><?php echo wp_kses_post($this->get_render_attribute_string('slide')); ?>>
                                    <?php wc_get_template_part('content', 'product'); ?>
                                </div>
                            <?php endwhile; ?>
                        </div>

                        <?php if ( 'yes' === ($settings['show_arrows'] ?? 'yes') ) : ?>
                            <div class="sifency-slider-nav-container">
                            <div class="swiper-button-prev sifency-slider-nav-arrow sifency-slider-nav-prev"><i class="icon-left"></i></div>
                            <div class="swiper-button-next sifency-slider-nav-arrow sifency-slider-nav-next"><i class="icon-right"></i></div>
                            </div>
                        <?php endif; ?>

                        <?php if ( ! empty($settings['show_pagination']) ) : ?>
                            <div class="swiper-pagination"></div>
                        <?php endif; ?>
                    </div>
                <?php else : ?>
                    <?php

                    $columns = !empty($settings['columns']) ? $settings['columns'] : 3;
                    wc_set_loop_prop('columns', $columns);

                    woocommerce_product_loop_start();
                    ?>
                    <?php while ( $related_query->have_posts() ) : $related_query->the_post(); ?>
                        <?php wc_get_template_part('content', 'product'); ?>
                    <?php endwhile; ?>
                    <?php woocommerce_product_loop_end(); ?>
                <?php endif; ?>
            </section>
        </div>
        <?php

        // --- Cleanup ---
        if ( 'child' === ($settings['sifency_animation_target'] ?? 'wrapper') ) {
            remove_filter('woocommerce_post_class', [ $this, '_filter_product_class' ], 10, 2);
        }

        wp_reset_postdata();

        // Restore global product
        if ( $original_product ) {
            $GLOBALS['product'] = $original_product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
        }
    }

    public function _filter_product_class( $classes, $product ) {
        if ( ! $this->animation_manager_instance ) {
            return $classes;
        }

        $animation_attrs = $this->animation_manager_instance->get_item_attributes([]);
        if ( isset($animation_attrs['class']) && ! empty($animation_attrs['class']) ) {
            $classes[] = $animation_attrs['class'];
        }

        return $classes;
    }

    private function _get_preview_product() {
        $query = new \WP_Query([
            'post_type'      => 'product',
            'posts_per_page' => 1,
            'orderby'        => 'date',
            'order'          => 'DESC',
            'post_status'    => 'publish',
        ]);

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

        return false;
    }
}