<?php
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

class WAFDAE_Dokan_Products_Widget extends Widget_Base
{
    public function __construct($data = [], $args = null)
    {
        parent::__construct($data, $args);
        wp_register_style('dokan-store-products', plugin_dir_url(__DIR__) . 'assets/css/dokan-store-products.css', '1.0.0');


    }

	public function get_style_depends()
	{
		return ['dokan-store-products'];
	}

    public function get_name()
    {
        return 'dokan_products';
    }

    public function get_title()
    {
        return __('Dokan Store Products', 'wpsaad-addons-for-dokan-and-elementor');
    }

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

    public function get_categories()
    {
        return ['wpsaad'];
    }

    protected function _register_controls()
    {
        // Content Section
        $this->start_controls_section('content_section', [
            'label' => __('Content Settings', 'wpsaad-addons-for-dokan-and-elementor'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);


        // Control for Dokan Store ID
        $this->add_control('store_id', [
            'label' => __('Store ID', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'input_type' => 'number',
            'description' => __('Enter the Store ID to display products from a specific vendor. Leave blank to show vendors all products.', 'wpsaad-addons-for-dokan-and-elementor'),
            'default' => '',
            'dynamic'     => ['active' => true], // Enables dynamic tags
        ]);

        // WooCommerce Product Shortcode Attributes as Controls
        $this->add_control('limit', [
            'label' => __('Product Limit', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::NUMBER,
            'default' => 10,
            'description' => __('Set the maximum number of products to display.', 'wpsaad-addons-for-dokan-and-elementor'),
        ]);

        $this->add_control('columns', [
            'label' => __('Columns', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'options' => [
                '1' => __('1 Column', 'wpsaad-addons-for-dokan-and-elementor'),
                '2' => __('2 Columns', 'wpsaad-addons-for-dokan-and-elementor'),
                '3' => __('3 Columns', 'wpsaad-addons-for-dokan-and-elementor'),
                '4' => __('4 Columns', 'wpsaad-addons-for-dokan-and-elementor'),
                '5' => __('5 Columns', 'wpsaad-addons-for-dokan-and-elementor'),
            ],
            'default' => '3',
        ]);

        $this->add_control('orderby', [
            'label' => __('Order By', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'options' => [
                'date' => __('Date', 'wpsaad-addons-for-dokan-and-elementor'),
                'title' => __('Title', 'wpsaad-addons-for-dokan-and-elementor'),
                'price' => __('Price', 'wpsaad-addons-for-dokan-and-elementor'),
                'rand' => __('Random', 'wpsaad-addons-for-dokan-and-elementor'),
                'popularity' => __('Popularity', 'wpsaad-addons-for-dokan-and-elementor'),
            ],
            'default' => 'date',
        ]);

        $this->add_control('order', [
            'label' => __('Order', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'options' => [
                'ASC' => __('Ascending', 'wpsaad-addons-for-dokan-and-elementor'),
                'DESC' => __('Descending', 'wpsaad-addons-for-dokan-and-elementor'),
            ],
            'default' => 'DESC',
        ]);

        $this->add_control('category', [
            'label' => __('Product Category', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'description' => __('Enter a category slug to filter products.', 'wpsaad-addons-for-dokan-and-elementor'),
            'default' => '',
            'dynamic'     => ['active' => true], // Enables dynamic tags
        ]);

        $this->add_control('tag', [
            'label' => __('Product Tag', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'description' => __('Enter a tag slug to filter products.', 'wpsaad-addons-for-dokan-and-elementor'),
            'default' => '',
            'dynamic'     => ['active' => true], // Enables dynamic tags
        ]);

        //(on_sale , best_selling) Not working due to woocommerce shorcode restictions 
        //Only Works alone and with all products

        // $this->add_control('on_sale', [
        //     'label' => __('On Sale Products Only', 'wpsaad-addons-for-dokan-and-elementor'),
        //     'type' => \Elementor\Controls_Manager::SWITCHER,
        //     'description' => __('Show only products that are currently on sale.', 'wpsaad-addons-for-dokan-and-elementor'),
        // ]);

        // $this->add_control('best_selling', [
        //     'label' => __('Best Selling Products', 'wpsaad-addons-for-dokan-and-elementor'),
        //     'type' => \Elementor\Controls_Manager::SWITCHER,
        //     'description' => __('Show only best-selling products.', 'wpsaad-addons-for-dokan-and-elementor'),
        // ]);

        $this->add_control('featured', [
            'label' => __('Featured Products Only', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'description' => __('Show only featured products.', 'wpsaad-addons-for-dokan-and-elementor'),
        ]);

        $this->end_controls_section();

        // Style Section
        $this->start_controls_section('item_style_section', [
            'label' => __('Item', 'wpsaad-addons-for-dokan-and-elementor'),
            'tab' => \Elementor\Controls_Manager::TAB_STYLE,
        ]);

        $this->add_control('columns_gap', [
            'label' => esc_html__( 'Columns Gap', 'wpsaad-addons-for-dokan-and-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', 'em', 'rem', 'custom' ],
            'default' => [
                'size' => 20,
            ],
            'tablet_default' => [
                'size' => 20,
            ],
            'mobile_default' => [
                'size' => 20,
            ],
            'range' => [
                'px' => [
                    'min' => 0,
                    'max' => 100,
                ],
            ],
            'selectors' => [
                '{{WRAPPER}} .product-grid-item' => 'padding-left: {{SIZE}}{{UNIT}}',
                '{{WRAPPER}} .product-grid-item' => 'padding-right: {{SIZE}}{{UNIT}}'

            ],
        ]);

        $this->add_control('rows_gap', [
            'label' => esc_html__( 'Row Gap', 'wpsaad-addons-for-dokan-and-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', 'em', 'rem', 'custom' ],
            'default' => [
                'size' => 20,
            ],
            'tablet_default' => [
                'size' => 20,
            ],
            'mobile_default' => [
                'size' => 20,
            ],
            'range' => [
                'px' => [
                    'min' => 0,
                    'max' => 100,
                ],
            ],
        'selectors' => [
                '{{WRAPPER}} .product-grid-item' => 'padding-top: {{SIZE}}{{UNIT}}',
                '{{WRAPPER}} .product-grid-item' => 'padding-bottom: {{SIZE}}{{UNIT}}'

            ],

        ]);
        $this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name' => 'item_border',
				'selector' => '{{WRAPPER}} .woocommerce ul.products li.product a.woocommerce-loop-product__link,'.
            '{{WRAPPER}} .woocommerce .products .product div.product-wrapper',//woodmart integeration
				'separator' => 'before',
			]
		);

		$this->add_responsive_control(
			'item_border_radius',
			[
				'label' => esc_html__('Border Radius', 'wpsaad-addons-for-dokan-and-elementor'),
				'type' => Controls_Manager::DIMENSIONS,
				'size_units' => ['px', '%', 'em', 'rem', 'custom'],
				'selectors' => [
					'{{WRAPPER}} .woocommerce ul.products li.product a.woocommerce-loop-product__link' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                    '{{WRAPPER}} .woocommerce .products .product div.product-wrapper' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			[
				'name' => 'item_box_shadow',
				'exclude' => [
					'box_shadow_position',
				],
				'selector' => '{{WRAPPER}} .woocommerce ul.products li.product a.woocommerce-loop-product__link,'.
                '{{WRAPPER}} .woocommerce .products .product div.product-wrapper',//woodmart integeration
			]
		);

        $this->add_group_control(\Elementor\Group_Control_Typography::get_type(), [
            'name' => 'title_typography',
            'label' => __('Title Typography', 'wpsaad-addons-for-dokan-and-elementor'),
            'selector' => '{{WRAPPER}} .woocommerce .products .product .woocommerce-loop-product__title,'.
            '{{WRAPPER}} .product-grid-item :is(.wd-entities-title,.wd-product-cats,.wd-product-brands-links)',
        ]);
        
        $this->add_control('title_color', [
            'label' => __('Title Color', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .woocommerce .products .product .woocommerce-loop-product__title' => 'color: {{VALUE}};',
            ],
        ]);

        $this->add_control('price_color', [
            'label' => __('Price Color', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .woocommerce .products .product.sale .price ins .amount' => 'color: {{VALUE}};',
                '{{WRAPPER}} .woocommerce .products .product:not(.sale) .price .amount' => 'color: {{VALUE}};',
            ],
        ]);

        $this->add_control('sale_price_color', [
            'label' => __('Sale Price Color', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .woocommerce .products .product.sale .price del .amount' => 'color: {{VALUE}};',
            ],
        ]);


        $this->add_control('button_color', [
            'label' => __('Button Color', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .woocommerce .products .product .button' => 'color: {{VALUE}};',
            ],
        ]);

        $this->add_control('button_background', [
            'label' => __('Button Background', 'wpsaad-addons-for-dokan-and-elementor'),
            'type' => \Elementor\Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .woocommerce .products .product .button' => 'background-color: {{VALUE}};',
            ],
        ]);

        $this->end_controls_section();
        $this->start_controls_section(
			'section_style_image',
			[
				'label' => esc_html__('Image', 'wpsaad-addons-for-dokan-and-elementor'),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_responsive_control(
			'width',
			[
				'label' => esc_html__('Width', 'wpsaad-addons-for-dokan-and-elementor'),
				'type' => Controls_Manager::SLIDER,
				'default' => [
					'unit' => '%',
				],
				'tablet_default' => [
					'unit' => '%',
				],
				'mobile_default' => [
					'unit' => '%',
				],
				'size_units' => ['px', '%', 'em', 'rem', 'vw', 'custom'],
				'range' => [
					'%' => [
						'min' => 1,
						'max' => 100,
					],
					'px' => [
						'min' => 1,
						'max' => 1000,
					],
					'vw' => [
						'min' => 1,
						'max' => 100,
					],
				],
				'selectors' => [
					'{{WRAPPER}} .woocommerce .products .product a img' => 'width: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'space',
			[
				'label' => esc_html__('Max Width', 'wpsaad-addons-for-dokan-and-elementor'),
				'type' => Controls_Manager::SLIDER,
				'default' => [
					'unit' => '%',
				],
				'tablet_default' => [
					'unit' => '%',
				],
				'mobile_default' => [
					'unit' => '%',
				],
				'size_units' => ['px', '%', 'em', 'rem', 'vw', 'custom'],
				'range' => [
					'%' => [
						'min' => 1,
						'max' => 100,
					],
					'px' => [
						'min' => 1,
						'max' => 1000,
					],
					'vw' => [
						'min' => 1,
						'max' => 100,
					],
				],
				'selectors' => [
					'{{WRAPPER}} .woocommerce .products .product a img' => 'max-width: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'height',
			[
				'label' => esc_html__('Height', 'wpsaad-addons-for-dokan-and-elementor'),
				'type' => Controls_Manager::SLIDER,
				'size_units' => ['px', '%', 'em', 'rem', 'vh', 'custom'],
				'range' => [
					'px' => [
						'min' => 1,
						'max' => 500,
					],
					'vh' => [
						'min' => 1,
						'max' => 100,
					],
				],
				'selectors' => [
					'{{WRAPPER}} .woocommerce .products .product a img' => 'height: {{SIZE}}{{UNIT}};',
				],
			]
		);
		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name' => 'image_border',
				'selector' => '{{WRAPPER}} .woocommerce .products .product a img',
				'separator' => 'before',
			]
		);

		$this->add_responsive_control(
			'image_border_radius',
			[
				'label' => esc_html__('Border Radius', 'wpsaad-addons-for-dokan-and-elementor'),
				'type' => Controls_Manager::DIMENSIONS,
				'size_units' => ['px', '%', 'em', 'rem', 'custom'],
				'selectors' => [
					'{{WRAPPER}} .woocommerce .products .product a img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			[
				'name' => 'image_box_shadow',
				'exclude' => [
					'box_shadow_position',
				],
				'selector' => '{{WRAPPER}} .woocommerce .products .product a img',
			]
		);

		$this->end_controls_section();

        //end style section
    }

    protected function render()
    {


        $settings = $this->get_settings_for_display();
        $store_id = $settings['store_id'];

        // Prepare WooCommerce product arguments
        $query_args = [
            'post_type' => 'product',
            'limit' => $settings['limit'],
            'columns' => $settings['columns'],
            'orderby' => $settings['orderby'],
            'order' => $settings['order'],
        ];

        // If Store ID is provided, filter products by vendor meta
        if ($store_id) {

            //enable author args for stores
            function htdat_shortcode_atts_products($out, $pairs, $atts, $shortcode)
            {
                if (isset($atts['author'])) $out['author'] = $atts['author'];
                return $out;
            }
            add_filter('shortcode_atts_products', 'htdat_shortcode_atts_products', 10, 4);

            function htdat_woocommerce_shortcode_products_query($query_args, $attributes)
            {
                if (isset($attributes['author'])) $query_args['author'] = $attributes['author'];
                return $query_args;
            }
            add_filter('woocommerce_shortcode_products_query', 'htdat_woocommerce_shortcode_products_query', 10, 2);

            $query_args['author'] = $store_id;
        }


        //(on_sale , best_selling) Not working due to woocommerce shorcode restictions 
        //Only Works alone and with all products

        // if ($settings['on_sale'] === 'yes') {
        //     $query_args['on_sale'] = true;
        // }
        // if ($settings['best_selling'] === 'yes') {
        //     $query_args['best_selling'] = true;
        // }
        if ($settings['featured'] === 'yes') {
            $query_args['visibility'] = 'featured';
        }
        if (!empty($settings['category'])) {
            $query_args['category'] = $settings['category'];
        }
        if (!empty($settings['tag'])) {
            $query_args['tag'] = $settings['tag'];
        }




        // Render WooCommerce products using the shortcode
        $shortcode = '[products ' . http_build_query($query_args, '', ' ') . ']';

        echo do_shortcode($shortcode);

        // $best_selling= dokan()->product->best_selling($query_args);
        // // var_dump($best_selling);
        // woocommerce_product_loop_start();

        // while ( $best_selling->have_posts() ) {
        //     $best_selling->the_post();

        //   wc_get_template_part( 'content', 'product' );

        // }
        // woocommerce_product_loop_end();

        //----------
        // $best_selling_query = dokan_get_best_selling_products( $settings['limit'], $store_id );

        // $best_selling_query = wc_get_products( $query_args );

// woocommerce_product_loop_start();

//     foreach ( $best_selling_query as $product ) {
//         $GLOBALS['post'] = get_post( $product->id ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
//         setup_postdata( $GLOBALS['post'] );


//         // Render product template.
//         wc_get_template_part( 'content', 'product' );

//     }

// woocommerce_product_loop_end();


        // woocommerce_product_loop_start();

        // while ( $best_selling_query->have_posts() ) {
        //     $best_selling_query->the_post();
        //   wc_get_template_part( 'content', 'product' );
        // }

        // if (empty($best_selling_query)) {
        //     echo __('No products found.', 'wpsaad-addons-for-dokan-and-elementor');
        //     return;
        // }


        // woocommerce_product_loop_end();

    }
}
