<?php
/**
 * ZMND WooCommerce Product Grid Widget
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

require_once WS_PATH . 'elementor/zmnd/includes/ws-zmnd-widget-base.php';

class WS_ZMND_Woo_Product_Grid_Widget extends WS_ZMND_Widget_Base {

    /**
     * Get widget name
     */
    public function get_name() {
        return 'ws_zmnd_woo_product_grid';
    }

    /**
     * Get widget title
     */
    public function get_title() {
        return esc_html__('WooCommerce Product Grid', 'watson');
    }

    /**
     * Get widget icon
     */
    public function get_icon() {
        return 'eicon-products';
    }

    /**
     * Get widget categories
     */
    public function get_categories() {
        return ['ws-category'];
    }

    /**
     * Get widget keywords
     */
    public function get_keywords() {
        return ['woocommerce', 'products', 'grid', 'shop', 'zmnd', 'watson'];
    }

    /**
     * Get script depends
     */
    public function get_script_depends() {
        return [];
    }
    
    /**
     * Get style depends
     */
    public function get_style_depends() {
        return ['ws-zmnd-widgets', 'ws-zmnd-woo-product-grid'];
    }

    /**
     * Register widget controls
     */
    protected function register_controls() {
        $this->start_controls_section(
            'ws_content_section',
            [
                'label' => esc_html__('Content', 'watson'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'ws_product_type',
            [
                'label'   => esc_html__('Product Type', 'watson'),
                'type'    => \Elementor\Controls_Manager::SELECT,
                'default' => 'products',
                'options' => [
                    'products' => esc_html__('Products', 'watson'),
                    'categories' => esc_html__('Categories', 'watson'),
                ],
            ]
        );
        
        $this->add_control(
            'ws_products_per_page',
            [
                'label' => esc_html__('Products Per Page', 'watson'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'min' => 1,
                'max' => 50,
                'step' => 1,
                'default' => 6,
                'condition' => [
                    'ws_product_type' => 'products',
                ],
            ]
        );
        
        $this->add_control(
            'ws_add_to_cart_text',
            [
                'label' => esc_html__('Add to Cart Button Text', 'watson'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => function_exists('watson_woo_get_add_to_cart_text') ? watson_woo_get_add_to_cart_text() : esc_html__('Add to cart', 'watson'),
                'placeholder' => esc_html__('Enter button text', 'watson'),
                'condition' => [
                    'ws_product_type' => 'products',
                ],
                'description' => esc_html__('Customize the text displayed on the Add to Cart button.', 'watson'),
            ]
        );
        
        $this->add_control(
            'ws_categories_per_page',
            [
                'label' => esc_html__('Categories Per Page', 'watson'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'min' => 1,
                'max' => 50,
                'step' => 1,
                'default' => 4,
                'condition' => [
                    'ws_product_type' => 'categories',
                ],
            ]
        );
        
        $this->add_control(
            'ws_product_columns',
            [
                'label' => esc_html__('Columns', 'watson'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => '2',
                'options' => [
                    '1' => esc_html__('1', 'watson'),
                    '2' => esc_html__('2', 'watson'),
                    '3' => esc_html__('3', 'watson'),
                    '4' => esc_html__('4', 'watson'),
                ],
            ]
        );
        
        $this->add_control(
            'ws_product_order',
            [
                'label' => esc_html__('Order', 'watson'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'desc',
                'options' => [
                    'asc' => esc_html__('ASC', 'watson'),
                    'desc' => esc_html__('DESC', 'watson'),
                ],
                'condition' => [
                    'ws_product_type' => 'products',
                ],
            ]
        );
        
        $this->add_control(
            'ws_product_orderby',
            [
                'label' => esc_html__('Order By', 'watson'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'date',
                'options' => [
                    'date' => esc_html__('Date', 'watson'),
                    'title' => esc_html__('Title', 'watson'),
                    'price' => esc_html__('Price', 'watson'),
                    'popularity' => esc_html__('Popularity', 'watson'),
                    'rating' => esc_html__('Rating', 'watson'),
                    'rand' => esc_html__('Random', 'watson'),
                ],
                'condition' => [
                    'ws_product_type' => 'products',
                ],
            ]
        );
        
        $this->add_control(
            'ws_show_category_count',
            [
                'label' => esc_html__('Show Category Count', 'watson'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Show', 'watson'),
                'label_off' => esc_html__('Hide', 'watson'),
                'return_value' => 'yes',
                'default' => 'no',
                'condition' => [
                    'ws_product_type' => 'categories',
                ],
            ]
        );
        
        // Добавляем настройку для кастомной иконки корзины
        $this->add_control(
            'ws_custom_cart_icon',
            [
                'label' => esc_html__('Custom Cart Icon', 'watson'),
                'type' => \Elementor\Controls_Manager::MEDIA,
                'default' => [
                    'url' => '',
                ],
                'description' => esc_html__('Upload a custom cart icon or leave empty to use the default icon.', 'watson'),
                'condition' => [
                    'ws_product_type' => 'products',
                ],
            ]
        );
        
        $this->add_control(
            'ws_use_svg_icon',
            [
                'label' => esc_html__('Use SVG Icon', 'watson'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'watson'),
                'label_off' => esc_html__('No', 'watson'),
                'return_value' => 'yes',
                'default' => 'yes',
                'condition' => [
                    'ws_product_type' => 'products',
                    'ws_custom_cart_icon[url]' => '',
                ],
            ]
        );
        
        $this->end_controls_section();
        
        // Style Tab
        $this->start_controls_section(
            'ws_style_section',
            [
                'label' => esc_html__('Style', 'watson'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );
        
        $this->add_control(
            'ws_product_title_color',
            [
                'label' => esc_html__('Title Color', 'watson'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .ws-product-title a' => 'color: {{VALUE}}',
                ],
            ]
        );
        
        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'ws_product_title_typography',
                'label' => esc_html__('Title Typography', 'watson'),
                'selector' => '{{WRAPPER}} .ws-product-title a',
            ]
        );
        
        $this->add_control(
            'ws_product_price_color',
            [
                'label' => esc_html__('Price Color', 'watson'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .ws-product-price .price' => 'color: {{VALUE}}',
                ],
                'condition' => [
                    'ws_product_type' => 'products',
                ],
            ]
        );
        
        $this->add_control(
            'ws_product_button_color',
            [
                'label' => esc_html__('Button Color', 'watson'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .ws-product-link a.button' => 'background-color: {{VALUE}}',
                ],
                'condition' => [
                    'ws_product_type' => 'products',
                ],
            ]
        );
        
        $this->add_control(
            'ws_product_button_text_color',
            [
                'label' => esc_html__('Button Icon Color', 'watson'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .ws-product-link a.button svg path' => 'stroke: {{VALUE}}',
                ],
                'condition' => [
                    'ws_product_type' => 'products',
                    'ws_use_svg_icon' => 'yes',
                    'ws_custom_cart_icon[url]' => '',
                ],
            ]
        );
        
        $this->end_controls_section();
    }

    /**
     * Render widget output on the frontend
     */
    protected function render() {
        $settings = $this->get_settings_for_display();
        $product_type = $settings['ws_product_type'];
        
        echo '<div class="row ws-woo-feed">';
        
        if ($product_type === 'categories') {
            $this->render_product_categories($settings);
        } else {
            $this->render_products($settings);
        }
        
        echo '</div>';
    }
    
    /**
     * Render product categories
     */
    private function render_product_categories($settings) {
        $categories_per_page = $settings['ws_categories_per_page'];
        $show_count = $settings['ws_show_category_count'];
        
        $args = array(
            'taxonomy'     => 'product_cat',
            'orderby'      => 'name',
            'show_count'   => 0,
            'pad_counts'   => 0,
            'hierarchical' => 1,
            'title_li'     => '',
            'hide_empty'   => 1,
            'number'       => $categories_per_page
        );
        
        $product_categories = get_terms($args);
        
        if (!empty($product_categories)) {
            echo '<div class="ws-woocommerce-product-category">';
            
            $counter = 0;
            foreach ($product_categories as $category) {
                $category_id = $category->term_id;
                $category_name = $category->name;
                $category_link = get_term_link($category_id, 'product_cat');
                $thumbnail_id = get_term_meta($category_id, 'thumbnail_id', true);
                
                // Определяем класс для элемента
                $item_class = ($counter % 2 === 0) ? 'first' : 'last';
                $counter++;
                
                echo '<div class="product-category product ' . esc_attr($item_class) . '">';
                echo '<a aria-label="Visit product category ' . esc_attr($category_name) . '" href="' . esc_url($category_link) . '"></a>';
                
                echo '<div class="ws-product-media"><a aria-label="Visit product category ' . esc_attr($category_name) . '" href="' . esc_url($category_link) . '"></a>';
                
                echo '<a aria-label="Visit product category ' . esc_attr($category_name) . '" href="' . esc_url($category_link) . '">';
                
                if ($thumbnail_id) {
                    $image = wp_get_attachment_image(
                        $thumbnail_id,
                        'woocommerce_thumbnail',
                        false,
                        array('alt' => $category_name)
                    );
                    echo $image;
                } else {
                    echo wc_placeholder_img();
                }
                
                echo '</a></div>';
                
                echo '<div class="ws-product-content">';
                echo '<h3 class="ws-product-title">';
                echo '<a aria-label="Visit product category ' . esc_attr($category_name) . '" href="' . esc_url($category_link) . '">' . esc_html($category_name) . '</a>';
                echo '</h3>';
                echo '<!-- /.ws-product-title -->';
                echo '</div>';
                
                echo '</div>';
            }
            
            echo '</div>';
        }
    }
    
    /**
     * Render cart icon based on settings
     * 
     * @param array $settings Widget settings
     * @param bool $include_text Whether to include button text
     * @return string HTML code for cart icon and button text
     */
    private function render_cart_icon($settings, $include_text = false) {
        $icon = '';
        
        if (!empty($settings['ws_custom_cart_icon']['url'])) {
            // Используем кастомную иконку, если она загружена
            $custom_icon_url = $settings['ws_custom_cart_icon']['url'];
            $icon = '<img src="' . esc_url($custom_icon_url) . '" alt="Cart" class="ws-cart-icon">';
        } else if ($settings['ws_use_svg_icon'] === 'yes') {
            // Используем новую SVG иконку
            $icon = '<svg class="addcart" enable-background="new 0 0 64 64" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg"><g><path d="m55.5 39.6c-1-5.7-2-11.5-3-17.2-.3-1.8-.6-3.7-1-5.5-.6-3.4-3.2-6.3-6.7-6.9-1.7-.3-3.5-.2-5.1-.2-3 0-6 0-9.1 0-2.7 0-5.3 0-8 0-2.4 0-4.6.1-6.7 1.5-1.8 1.3-3 3.1-3.4 5.3-1.5 8.6-3.1 17.2-4.5 25.7-.7 4.1 1.1 8.3 4.7 10.4 2 1.2 4.2 1.4 6.4 1.4h16.4 8c1.7 0 3.4.1 5-.3 4.2-1 7.2-4.8 7.5-9.1.3-1.6-.2-3.4-.5-5.1zm-4.9 10c-1.6 1.4-3.6 1.5-5.6 1.5-2.1 0-4.2 0-6.4 0-5.6 0-11.2 0-16.7 0-1.4 0-2.7 0-4.1 0-3.5 0-6.5-2.5-6.9-6-.2-1.5.2-3 .5-4.4.4-2.5.9-5 1.3-7.5.7-5.3 1.9-10.5 2.8-15.8.6-3 2.9-4.6 5.9-4.6h6.2 15.1c2.8 0 5.2 1.4 5.9 4.2.3 1.2.4 2.4.6 3.6 1 5.5 1.9 10.9 2.9 16.4.7 4.3 2.4 9.4-1.5 12.6z"></path><path d="m38.5 17.6v3.7c-.1 2.1-1.2 4.2-3.1 5.3-3.9 2.4-9.2 0-9.9-4.6-.2-1.4-.1-2.9-.1-4.3 0-1.9-3-1.9-3 0 0 1.6-.1 3.2.1 4.7.4 2.9 2.2 5.5 4.7 7 5.3 3 12.3.1 13.9-5.8.5-1.9.3-3.9.3-5.9.1-2.1-2.9-2.1-2.9-.1z"></path></g></svg>';
        } else {
            // Используем стандартную SVG иконку
            $icon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M7.5 7.66952V6.69952C7.5 4.44952 9.31 2.23952 11.56 2.02952C14.24 1.76952 16.5 3.87952 16.5 6.50952V7.88952" stroke="#FAFBFC" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"></path><path d="M3.8108 16.56L4.0408 18.43C4.2608 20.39 4.9808 22 9.0008 22H15.0008C19.0208 22 19.7408 20.39 19.9508 18.43L20.7008 12.43C20.9708 9.99 20.2708 8 16.0008 8H8.0008C3.7308 8 3.0308 9.99 3.3008 12.43" stroke="#FAFBFC" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"></path><path d="M15.4941 12H15.5031" stroke="#FAFBFC" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8.49414 12H8.50312" stroke="#FAFBFC" stroke-linecap="round" stroke-linejoin="round"></path></svg>';
        }
        
        // Добавляем текст кнопки из настроек кастомайзера, если нужно
        if ($include_text) {
            // Проверяем, доступна ли функция из кастомайзера
            if (function_exists('watson_woo_get_add_to_cart_text')) {
                $button_text = watson_woo_get_add_to_cart_text();
            } else {
                $button_text = esc_html__('Add to cart', 'watson');
            }
            
            return $icon . '<span>' . esc_html($button_text) . '</span>';
        }
        
        return $icon;
    }
    
    /**
     * Render products
     */
    private function render_products($settings) {
        $products_per_page = $settings['ws_products_per_page'];
        $columns = $settings['ws_product_columns'];
        $orderby = $settings['ws_product_orderby'];
        $order = $settings['ws_product_order'];
        
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => $products_per_page,
            'orderby'        => $orderby,
            'order'          => $order,
        );
        
        // Исключаем продукты ремонта, если они есть
        $args['meta_query'] = array(
            array(
                'key'     => '_tech_repair_product',
                'compare' => 'NOT EXISTS',
            ),
        );
        
        $products = new WP_Query($args);
        
        if ($products->have_posts()) {
            $column_class = 'col-sm-' . (12 / intval($columns));
            
            while ($products->have_posts()) {
                $products->the_post();
                global $product;
                
                if (!$product || !$product->is_visible()) {
                    continue;
                }
                
                echo '<div class="' . esc_attr($column_class) . '">';
                echo '<article class="ws-product product type-product post-' . get_the_ID() . ' status-' . get_post_status() . ' ' . implode(' ', wc_get_product_class('', $product)) . '">';
                
                // Изображение продукта
                echo '<div class="ws-product-media">';
                echo '<a href="' . esc_url(get_the_permalink()) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
                echo woocommerce_get_product_thumbnail();
                echo '</a></div>';
                
                echo '<a href="' . esc_url(get_the_permalink()) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link"></a>';
                
                // Контент продукта
                echo '<div class="ws-product-content"><a href="' . esc_url(get_the_permalink()) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link"></a>';
                
                // Ссылка на продукт и кнопка добавления в корзину
                echo '<div class="ws-product-link"><a href="' . esc_url(get_the_permalink()) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link"></a>';
                
                // Кнопка добавления в корзину с текстом из настроек виджета
                // Используем текст из настроек виджета, если он задан, или из кастомайзера
                $button_text = !empty($settings['ws_add_to_cart_text']) ? $settings['ws_add_to_cart_text'] : (function_exists('watson_woo_get_add_to_cart_text') ? watson_woo_get_add_to_cart_text() : esc_html__('Add to cart', 'watson'));
                
                echo '<a href="?add-to-cart=' . esc_attr($product->get_id()) . '" data-quantity="1" class="button product_type_' . esc_attr($product->get_type()) . ' add_to_cart_button ajax_add_to_cart" data-product_id="' . esc_attr($product->get_id()) . '" data-product_sku="' . esc_attr($product->get_sku()) . '" aria-label="' . esc_attr__('Add to cart:', 'watson') . ' &quot;' . esc_attr(get_the_title()) . '&quot;" rel="nofollow" data-success_message="&quot;' . esc_attr(get_the_title()) . '&quot; ' . esc_attr__('has been added to your cart', 'watson') . '">' . $this->render_cart_icon($settings, true) . '</a>';
                
                echo '<div class="ws-product__mask">';
                echo '<svg width="81" height="27" viewBox="0 0 80 25" fill="none" xmlns="http://www.w3.org/2000/svg">';
                echo '<path fill-rule="evenodd" clip-rule="evenodd" d="M19.3641 10.883C14.6806 17.717 8.2843 25 0 25H80C71.716 25 65.319 17.717 60.636 10.883C56.1315 4.31097 48.5692 0 40 0C31.4308 0 23.8685 4.31097 19.3641 10.883Z"></path>';
                echo '</svg>';
                echo '</div>';
                
                echo '</div>';
                
                // Заголовок продукта
                echo '<h5 class="ws-product-title">';
                echo '<a href="' . esc_url(get_the_permalink()) . '">' . get_the_title() . '</a>';
                echo '</h5>';
                
                // Категория продукта
                echo '<div class="ws-product-cat">';
                echo wc_get_product_category_list($product->get_id(), ', ', '<span class="posted_in">', '</span>');
                echo '</div>';
                
                // Цена и футер продукта
                echo '<div class="ws-product-footer">';
                echo '<div class="ws-product-price">';
                echo wc_get_template_part('loop/price');
                echo '</div>';
                echo '</div>';
                
                echo '</div>';
                
                echo '</article>';
                echo '</div>';
            }
            
            wp_reset_postdata();
        }
    }
}
