<?php
// Brand Filter Widget
class Brand_Filter_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'brand-filter-widget',
            'description' => 'Adds a widget for filtering products based on brands.',
        );
        parent::__construct('brand_filter_widget', esc_html__('Kaveh Product Filter by Brand', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        ?>
        <div class="category-sidebar-box boxme">
            <div class="category-sidebar-box-heading">
                <i class="icon-filter"></i>
                <?php echo esc_html($instance['title']); ?>
            </div>
            <div class="category-sidebar-box-body">
                <ul class="category-sidebar-box-items brandhidden">
                    <input class="filterhiddeninputbrand" type="hidden" id="filters-brand" />
                    <?php
                    $current_brand = get_queried_object(); // Get the current brand object
                    $parent_id = 0;

                    if (is_object($current_brand) && isset($current_brand->term_id)) {
                        // Translate the current brand ID to current language
                        $parent_id = apply_filters('wpml_object_id', $current_brand->term_id, 'brands', true);
                    }

                    $this->display_subbrands($parent_id);
                    ?>
                </ul>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Recursive function to display subbrands
    public function display_subbrands($parent_id)
    {
        $subbrands = get_categories(array(
            'taxonomy' => 'brands',
            'parent' => $parent_id,
            'hide_empty' => false,
        ));

        if (!empty($subbrands)) {
            foreach ($subbrands as $brand) {
                // Translate brand ID to current language
                $translated_brand_id = apply_filters('wpml_object_id', $brand->term_id, 'brands', true);
                if (!$translated_brand_id) {
                    continue; // Skip if no translation exists
                }
                
                // Get translated brand object
                $translated_brand = get_term($translated_brand_id, 'brands');
                if (is_wp_error($translated_brand) || !$translated_brand) {
                    continue;
                }
                
                $sub_subbrands = get_categories(array(
                    'taxonomy' => 'brands',
                    'parent' => $translated_brand_id,
                    'hide_empty' => false,
                ));
                ?>
                <li class="<?php echo !empty($sub_subbrands) ? 'has-child' : ''; ?>">
                    <div class="form-check">
                        <input type="checkbox" name="brand" id="brand-<?php echo $translated_brand_id; ?>"
                            myid="<?php echo $translated_brand_id; ?>" class="form-check-input" />
                        <label for="brand-<?php echo $translated_brand_id; ?>" class="form-check-label"><?php echo esc_html($translated_brand->name); ?></label>
                    </div>
                    <?php if (!empty($sub_subbrands)): ?>
                        <span></span>
                        <ul>
                            <?php $this->display_subbrands($translated_brand_id); ?>
                        </ul>
                    <?php endif; ?>
                </li>
                <?php
            }
        }
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';

        // Widget title field
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Widget Title', 'kavehTheme'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }
}

// Category Filter Widget
class Category_Filter_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'category-filter-widget',
            'description' => 'Adds a widget for filtering products based on categories.',
        );
        parent::__construct('category_filter_widget', esc_html__('Kaveh Product Filter by Category', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        ?>
        <div class="category-sidebar-box boxme">
            <div class="category-sidebar-box-heading">
                <i class="icon-filter"></i>
                <?php echo esc_html($instance['title']); ?>
            </div>
            <div class="category-sidebar-box-body">
                <ul class="category-sidebar-box-items cathidden">
                    <input class="filterhiddeninput" type="hidden" id="filters-category" />
                    <?php
                    $current_category = get_queried_object(); // Get the current category object
                    $parent_id = 0;

                    if (is_object($current_category) && isset($current_category->term_id)) {
                        // Translate the current category ID to current language
                        $parent_id = apply_filters('wpml_object_id', $current_category->term_id, 'product_cat', true);
                    }

                    $this->display_subcategories($parent_id);
                    ?>
                </ul>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Recursive function to display subcategories
    public function display_subcategories($parent_id)
    {
        $subcategories = get_categories(array(
            'taxonomy' => 'product_cat',
            'parent' => $parent_id,
            'hide_empty' => false,
        ));

        if (!empty($subcategories)) {
            foreach ($subcategories as $category) {
                // Translate category ID to current language
                $translated_category_id = apply_filters('wpml_object_id', $category->term_id, 'product_cat', true);
                if (!$translated_category_id) {
                    continue; // Skip if no translation exists
                }
                
                // Get translated category object
                $translated_category = get_term($translated_category_id, 'product_cat');
                if (is_wp_error($translated_category) || !$translated_category) {
                    continue;
                }
                
                $sub_subcategories = get_categories(array(
                    'taxonomy' => 'product_cat',
                    'parent' => $translated_category_id,
                    'hide_empty' => false,
                ));
                ?>
                <li class="<?php echo !empty($sub_subcategories) ? 'has-child' : ''; ?>">
                    <div class="form-check">
                        <input type="checkbox" name="category" id="category-<?php echo $translated_category_id; ?>"
                            myid="<?php echo $translated_category_id; ?>" class="form-check-input" />
                        <label for="category-<?php echo $translated_category_id; ?>"
                            class="form-check-label"><?php echo esc_html($translated_category->name); ?></label>
                    </div>
                    <?php if (!empty($sub_subcategories)): ?>
                        <span></span>
                        <ul>
                            <?php $this->display_subcategories($translated_category_id); ?>
                        </ul>
                    <?php endif; ?>
                </li>
                <?php
            }
        }
    }


    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';

        // Widget title field
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Widget Title', 'kavehTheme'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }
}

// WooCommerce Attribute Widget
class WooCommerce_Attribute_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'woocommerce-attribute-widget',
            'description' => 'Adds a widget for selecting WooCommerce attributes and filtering products.',
        );
        parent::__construct('woocommerce_attribute_widget', esc_html__('Kaveh Product Filter by Attribute', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        $selected_attribute = isset($instance['selected_attribute']) ? $instance['selected_attribute'] : '';
        if ($selected_attribute) {
            $terms = get_terms(array(
                'taxonomy' => 'pa_' . $selected_attribute,
                'hide_empty' => false,
            ));

            if (!empty($terms)) {
                ?>
                <div class="category-sidebar-box boxme">
                    <div class="category-sidebar-box-heading">
                        <i class="icon-filter"></i>
                        <?php echo esc_html($instance['title']); ?>
                    </div>
                    <div class="category-sidebar-box-body">
                        <ul class="category-sidebar-box-items attrhidden">
                            <input class="attrhiddeninput" type="hidden" id="filters-category"
                                taxid="<?php echo 'pa_' . esc_attr($selected_attribute); ?>" />
                            <?php foreach ($terms as $term): 
                                // Translate term ID to current language
                                $translated_term_id = apply_filters('wpml_object_id', $term->term_id, 'pa_' . $selected_attribute, true);
                                if (!$translated_term_id) {
                                    continue; // Skip if no translation exists
                                }
                                
                                // Get translated term object
                                $translated_term = get_term($translated_term_id, 'pa_' . $selected_attribute);
                                if (is_wp_error($translated_term) || !$translated_term) {
                                    continue;
                                }
                            ?>
                                <li>
                                    <div class="form-check">
                                        <input type="checkbox" name="category" id="category-<?php echo esc_attr($translated_term->slug); ?>"
                                            myid="<?php echo esc_attr($translated_term->slug); ?>" class="form-check-input" />
                                        <label for="category-<?php echo esc_attr($translated_term->slug); ?>"
                                            class="form-check-label"><?php echo esc_html($translated_term->name); ?></label>
                                    </div>
                                </li>
                            <?php endforeach; ?>

                        </ul>
                    </div>
                </div>
                <?php
            }
        }

        echo $args['after_widget'];
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        $instance['selected_attribute'] = !empty($new_instance['selected_attribute']) ? sanitize_text_field($new_instance['selected_attribute']) : '';
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        $selected_attribute = !empty($instance['selected_attribute']) ? $instance['selected_attribute'] : '';

        // Widget title field
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Widget Title', 'kavehTheme'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('selected_attribute'); ?>"><?php esc_html_e('Select Attribute:', 'kavehTheme'); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id('selected_attribute'); ?>"
                name="<?php echo $this->get_field_name('selected_attribute'); ?>">
                <option value=""><?php esc_html_e('Select Attribute', 'kavehTheme'); ?></option>
                <?php
                $attributes = wc_get_attribute_taxonomies(); // Get all WooCommerce attributes
        
                foreach ($attributes as $attribute) {
                    $attribute_name = $attribute->attribute_name;
                    $selected = $selected_attribute === $attribute_name ? 'selected' : '';
                    ?>
                    <option value="<?php echo esc_attr($attribute_name); ?>" <?php echo $selected; ?>><?php echo esc_html($attribute_name); ?></option>
                    <?php
                }
                ?>
            </select>
        </p>
        <?php
    }
}

// Range Price Widget
class Range_Price_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'range-price-widget',
            'description' => 'Adds a widget for filtering products based on price range.',
        );
        parent::__construct('range_price_widget', esc_html__('By Price', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        ?>
        <div class="category-sidebar-box filter-price">
            <div class="category-sidebar-box-heading">
                <i class="icon-filter"></i>
                <?php echo esc_html($instance['title']); ?>
            </div>
            <div class="category-sidebar-box-body">
                <div id="category-price"></div>
                <div class="filter-price-value d-flex align-items-center">
                    <span> <?php esc_html_e('From', 'kavehTheme'); ?> </span>
                    <input type="text" id="category-price-min" class="form-control text-left" />
                </div>
                <div class="filter-price-value d-flex align-items-center">
                    <span> <?php esc_html_e('To', 'kavehTheme'); ?> </span>
                    <input type="text" id="category-price-max" class="form-control text-left" />
                </div>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';

        // Widget title field
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Widget Title', 'kavehTheme'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }
}

// Fast Send Widget
class Fast_Send_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'fast-send-widget',
            'description' => 'Adds a widget for filtering products by "Only Sale" option.',
        );
        parent::__construct('fast_send_widget', esc_html__('Only Sale Items', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        ?>
        <div class="category-sidebar-box">
            <div class="category-sidebar-box-heading">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="onlysale">
                    <label class="form-check-label" for="onlysale"> <?php esc_html_e('Only Sale Items', 'kavehTheme'); ?> </label>
                </div>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        // No options to configure
    }
}

// Exists Products Widget
class Exists_Products_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'exists-products-widget',
            'description' => 'Adds a widget for filtering products by "Exists Products" option.',
        );
        parent::__construct('exists_products_widget', esc_html__('Only Available', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        ?>
        <div class="category-sidebar-box exists-products">
            <div class="category-sidebar-box-heading">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="exists-products">
                    <label class="form-check-label" for="exists-products"> <?php esc_html_e('Only Available Products', 'kavehTheme'); ?> </label>
                </div>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        // No options to configure
    }
}

// Latest Articles Widget
class Latest_Articles_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'latest-articles-widget',
            'description' => 'Adds a widget for displaying the latest articles.',
        );
        parent::__construct('latest_articles_widget', esc_html__('Latest Articles', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }

        // Widget content
        ?>
        <div class="lapost">
            <h5><?php esc_html_e('Latest Articles', 'kavehTheme'); ?></h5>
            <p><?php esc_html_e('Latest Published News', 'kavehTheme'); ?></p>
            <ul class="footer-three-articles">
                <?php
                // WP_Query args with WPML compatibility
                $q_query_args = array(
                    'post_type' => array('post'),
                    'posts_per_page' => 4,
                    'order' => 'DESC',
                    'orderby' => 'date',
                    'suppress_filters' => false, // Allow WPML to filter posts by language
                );
                
                // The Query
                $query = new WP_Query($q_query_args);
                // The Loop
                if ($query->have_posts()) {
                    while ($query->have_posts()) {
                        $query->the_post();
                        ?>
                        <li class="d-flex align-items-center">
                            <img src="<?php the_post_thumbnail_url('full'); ?>" alt="<?php esc_attr_e('article', 'kavehTheme'); ?>" class="d-block w-100" />
                            <div class="detail w-100">
                                <h2 class="mb-0 text-nowrap overflow-hidden">
                                    <a href="<?php the_permalink(); ?>"><?php 
                                        $title = get_the_title();
                                        echo esc_html(wp_trim_words($title, 6)); 
                                    ?></a>
                                </h2>
                                <span class="d-block text-nowrap overflow-hidden"><?php 
                                    $excerpt = get_the_excerpt();
                                    echo esc_html(wp_trim_words($excerpt, 7)); 
                                ?></span>
                            </div>
                        </li>
                        <?php
                    }
                }
                // Reset Original Post Data
                wp_reset_postdata();
                ?>
            </ul>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';

        // Widget title field
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Widget Title', 'kavehTheme'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }
}

// Blog Category Widget
class Blog_Category_Widget extends WP_Widget
{

    // Widget setup
    public function __construct()
    {
        $widget_options = array(
            'classname' => 'blog-category-widget',
            'description' => 'Adds a widget for displaying blog categories.',
        );
        parent::__construct('blog_category_widget', esc_html__('Blog Categories', 'kavehTheme'), $widget_options);
    }

    // Output the widget
    public function widget($args, $instance)
    {
        echo $args['before_widget'];

        // Widget content
        ?>
        <div class="lapost">
            <div class="category-sidebar-box">
                <div class="category-sidebar-box-heading">
                    <i class="icon-filter"></i>
                    <?php esc_html_e('Blog Categories', 'kavehTheme'); ?>
                </div>
                <div class="category-sidebar-box-body">
                    <ul class="category-sidebar-box-items">
                        <?php 
                        $categories = get_categories(array(
                            'hide_empty' => false,
                        ));
                        
                        foreach ($categories as $category): 
                            // Translate category ID to current language
                            $translated_category_id = apply_filters('wpml_object_id', $category->term_id, 'category', true);
                            if (!$translated_category_id) {
                                continue; // Skip if no translation exists
                            }
                            
                            // Get translated category object
                            $translated_category = get_term($translated_category_id, 'category');
                            if (is_wp_error($translated_category) || !$translated_category) {
                                continue;
                            }
                        ?>
                            <li>
                                <a href="<?php echo esc_url(get_term_link($translated_category)); ?>">
                                    <?php echo esc_html($translated_category->name); ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    // Update the widget
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        return $instance;
    }

    // Widget form
    public function form($instance)
    {
        // No options to configure
    }
}