<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
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_Animation_Manager;
use \Sifency\Traits\Sifency_Elementor_Parity_Controls;
use \Sifency\Traits\Sifency_Products_Controls;

class Sifency_Widget_Products extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Products_Controls;

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

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

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

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

    public function get_keywords() {
        return ['woocommerce', 'products', 'shop', 'ecommerce', 'grid', 'sifency'];
    }

    public function get_style_depends() {
        return ['sifency-frontend-style', 'sifency-products-style'];
    }

    public function get_script_depends() {
        return ['sifency-frontend-script'];
    }
    
    protected function _get_tax_terms($taxonomy) {
        $terms = get_terms([
            'taxonomy' => $taxonomy,
            'hide_empty' => true,
        ]);
        
        if ( is_wp_error($terms) ) {
            return [];
        }

        $options = [];
        foreach ($terms as $term) {
            $options[$term->term_id] = $term->name;
        }
        return $options;
    }

    protected function register_controls() {
        if (!class_exists('woocommerce')) {
            $this->start_controls_section('woo_notice', ['label' => 'Notice']);
            $this->add_control('woo_notice_control', ['type' => Controls_Manager::RAW_HTML, 'raw' => '<div class="elementor-panel-alert elementor-panel-alert-warning">' . esc_html__('WooCommerce is not installed or active.', 'sifency-addons') . '</div>']);
            $this->end_controls_section();
            return;
        }

        $this->add_sifency_products_controls();
        Sifency_Elementor_Parity_Controls::register( $this);
        $this->add_sifency_animation_controls();
    }

    protected function render() {
        if ( ! class_exists( 'woocommerce' ) ) {
            echo '<div class="elementor-alert elementor-alert-warning">' . esc_html__( 'WooCommerce is not installed or active.', 'sifency-addons' ) . '</div>';
            return;
        }

        $settings = $this->get_settings_for_display();
        $animation_manager_instance = new Sifency_Animation_Manager($settings);

        $parity_pattern = $settings['parity_pattern'] ?? 'standard';
        $custom_positions = [];
        if ('custom' === $parity_pattern && !empty($settings['custom_even_positions'])) {
            $custom_positions = array_map('intval', explode(',', $settings['custom_even_positions']));
        }

        // --- Build Query ---
        $paged = get_query_var('paged') ? get_query_var('paged') : 1;
        $args = [
            'post_type' => 'product',
            'posts_per_page' => $settings['posts_per_page'],
            'paged' => $paged,
            'orderby' => $settings['orderby'],
            'order' => $settings['order'],
            'post_status' => 'publish',
        ];
        
        if ('sales' === $settings['orderby']) {
            $args['meta_key'] = 'total_sales';
            $args['orderby'] = 'meta_value_num';
        }

        // Source-based arguments
        switch ($settings['source']) {
            case 'sale':
                $args['post__in'] = array_merge([0], wc_get_product_ids_on_sale());
                break;
            case 'featured':
                $args['tax_query'][] = [
                    'taxonomy' => 'product_visibility',
                    'field' => 'name',
                    'terms' => 'featured',
                    'operator' => 'IN',
                ];
                break;
            case 'manual_selection':
                    if ( ! empty( $settings['manual_products'] ) ) {
                    $args['post__in'] = $settings['manual_products'];
                    $args['orderby'] = 'post__in';
                }
                break;
        }

        // Taxonomy query
        if (!empty($settings['include_categories']) || !empty($settings['exclude_categories'])) {
            $tax_query = [];
            if (!empty($settings['include_categories'])) {
                $tax_query[] = [
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => $settings['include_categories'],
                    'operator' => 'IN',
                ];
            }
            if (!empty($settings['exclude_categories'])) {
                $tax_query[] = [
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => $settings['exclude_categories'],
                    'operator' => 'NOT IN',
                ];
            }
            $args['tax_query'] = [['relation' => 'AND', ...$tax_query]];
        }
        
        $products_query = new \WP_Query($args);

        if ( ! $products_query->have_posts() ) {
            echo '<div class="elementor-alert elementor-alert-info">' . esc_html__( 'No products found matching your criteria.', 'sifency-addons' ) . '</div>';
            return;
        }

        $wrapper_classes = ['sifency-products-grid-wrapper'];
        $wrapper_attrs = $animation_manager_instance->get_wrapper_attributes($wrapper_classes);

        if ('yes' !== ($settings['show_rating'] ?? 'yes')) {
            remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5);
        }
        if ('yes' !== ($settings['show_badge'] ?? 'yes')) {
            remove_action('woocommerce_before_shop_loop_item_title', 'woocommerce_show_product_loop_sale_flash', 10);
        }
        ?>
        <div <?php 
            
            echo wp_kses_post( $wrapper_attrs ); ?>>
            <div class="woocommerce sifency-products-grid">
                <?php woocommerce_product_loop_start(); ?>
                <?php while ($products_query->have_posts()) : $products_query->the_post(); ?>
                    <?php
                    // Accessing the global $product object from WooCommerce.
                    global $product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                    
                    $current_position = $products_query->current_post + 1;
                    $parity_class = 'odd-item';
                    switch ($parity_pattern) {
                        case 'every_third':
                            if ($current_position % 3 === 0) {
                                $parity_class = 'even-item';
                            }
                            break;
                        case 'custom':
                            if (in_array($current_position, $custom_positions, true)) {
                                $parity_class = 'even-item';
                            }
                            break;
                        case 'standard':
                        default:
                            if ($current_position % 2 === 0) {
                                $parity_class = 'even-item';
                            }
                            break;
                    }

                    $product_classes = wc_get_product_class('', $product);
                    $product_classes[] = $parity_class;
                    $item_attrs = $animation_manager_instance->get_item_attributes($product_classes);

                    echo '<li ' . wp_kses_post( $item_attrs ) . '>';
                    do_action('woocommerce_before_shop_loop_item');
                    do_action('woocommerce_before_shop_loop_item_title');
                    do_action('woocommerce_shop_loop_item_title');
                    do_action('woocommerce_after_shop_loop_item_title');
                    do_action('woocommerce_after_shop_loop_item');

                    echo '</li>';
                    ?>
                <?php endwhile; ?>
                <?php woocommerce_product_loop_end(); ?>
            </div>

            <?php if ('yes' === ($settings['pagination_show'] ?? 'no') && $products_query->max_num_pages > 1) : ?>
                <nav class="sifency-pagination">
                    <?php
                    /* translators: Used for pagination navigation - previous page symbol. */
                    $prev_text = __( '&laquo;', 'sifency-addons' );

                    /* translators: Used for pagination navigation - next page symbol. */
                    $next_text = __( '&raquo;', 'sifency-addons' );

                    echo wp_kses_post(
                        paginate_links( [
                            'base'      => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
                            'total'     => $products_query->max_num_pages,
                            'current'   => max( 1, get_query_var( 'paged' ) ),
                            'format'    => '?paged=%#%',
                            'prev_text' => $prev_text,
                            'next_text' => $next_text,
                        ] )
                    );
                    ?>
                </nav>
            <?php endif; ?>
        </div>
        <?php
        
        // --- Cleanup ---
        // Restore hooks
        if ('yes' !== ($settings['show_rating'] ?? 'yes')) {
            add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5);
        }
        if ('yes' !== ($settings['show_badge'] ?? 'yes')) {
            add_action('woocommerce_before_shop_loop_item_title', 'woocommerce_show_product_loop_sale_flash', 10);
        }
        
        wp_reset_postdata();
    }

    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'])) {
            $classes[] = $animation_attrs['class'];
        }
        return $classes;
    }
}