<?php

namespace ThemesflatAddons\Widgets;

use  Elementor\Utils;
use  Elementor\Widget_Base;
use  Elementor\Controls_Manager;
use  Elementor\Group_Control_Image_Size;
use  Elementor\Group_Control_Typography;

if (!defined('ABSPATH')) {
    exit;
}

// Exit if accessed directly
class TFL_ProductsGrid_Widget extends TFL_Widget_Base
{
    public function get_name()
    {
        return 'tfl-product-grid';
    }

    public function get_title()
    {
        return __('Products Grid', 'themesflat');
    }

    public function get_icon()
    {
        return 'tfl-icon-pricing-table';
    }

    public function get_categories()
    {
        return array('themesflat-addons');
    }

    public function get_custom_help_url()
    {
        return 'https://themesflatelementor.com/docs/themesflat-addons/core-addons/posts-portfolio-grid/';
    }

    public function get_script_depends()
    {
        return [
            'isotope.pkgd',
            'imagesloaded.pkgd',
            'tfl-frontend-scripts',
            'tfl-product-scripts'
        ];
    }

    public function get_style_depends()
    {
        return ['tfl-frontend-styles', 'tfl-grid-styles', 'tfl-product-styles'];
    }

    protected function register_controls()
    {

        $this->start_controls_section('section_post_content', [
            'label' => __('Post Content', 'themesflat'),
            'condition' => [
            ],
        ]);
        $this->add_group_control(Group_Control_Image_Size::get_type(), [
            'name' => 'thumbnail_size',
            'label' => __('Image Size', 'themesflat'),
            'default' => 'large',
        ]);

        $this->end_controls_section();

    }

    protected function get_item_template_content($template_id, $settings)
    {
        /* Initialize the theme builder templates - Requires elementor pro plugin */

        if (!is_plugin_active('elementor-pro/elementor-pro.php')) {
            $output = tfl_template_error(__('Custom skin requires Elementor Pro but the plugin is not installed/active', 'themesflat'));
        } else {
            $output = tfl_get_item_template_content($template_id, $settings);
        }

        return $output;
    }

    protected function get_grid_template_content($template_id, $settings)
    {
        /* Initialize the theme builder templates - Requires elementor pro plugin */

        if (!is_plugin_active('elementor-pro/elementor-pro.php')) {
            $output = tfl_template_error(__('Custom skin requires Elementor Pro but the plugin is not installed/active', 'themesflat'));
        } else {
            $output = tfl_get_template_content($template_id, $settings);
        }

        return $output;
    }

    protected function get_item_template_options()
    {
        $template_options = array();
        /* Initialize the theme builder templates - Requires elementor pro plugin */

        if (!is_plugin_active('elementor-pro/elementor-pro.php')) {
            $template_options = [
                0 => __('No templates found. Elementor Pro is not installed/active', 'themesflat'),
            ];
        } else {
            $templates = tfl_get_themesflat_item_templates();
            //$template_options = [0 => __('Select a template', 'themesflat')];
            foreach ($templates as $template) {
                $template_options[$template->ID] = $template->post_title;
            }
        }

        return $template_options;
    }

    protected function get_grid_template_options()
    {
        $template_options = array();
        /* Initialize the theme builder templates - Requires elementor pro plugin */

        if (!is_plugin_active('elementor-pro/elementor-pro.php')) {
            $template_options = [
                0 => __('No templates found. Elementor Pro is not installed/active', 'themesflat'),
            ];
        } else {
            $templates = tfl_get_themesflat_grid_templates();
            //$template_options = [0 => __('Select a template', 'themesflat')];
            foreach ($templates as $template) {
                $template_options[$template->ID] = $template->post_title;
            }
        }

        return $template_options;
    }

    protected function get_item_templates($shortcode_pattern, $grid_template_content)
    {
        $matches = array();
        preg_match_all($shortcode_pattern, $grid_template_content, $matches);
        $attributes = array_pop($matches);
        // fetch last array element
        $item_templates = array();
        foreach ($attributes as $attribute) {
            list($key, $val) = explode("=", $attribute);
            $item_templates[] = trim($val, '"');
        }
        return $item_templates;
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        
        $settings['per_line'] = 4;
        $settings['per_line_tablet'] = 2;
        $settings['per_line_mobile'] = 1;
        $settings['layout_mode'] = 'fitRows';
        $settings['display_title'] = 'no';
        $settings['image_linkable'] = 'no';
        $settings['display_summary'] = 'no';
//        $settings['display_summary'] = 'no';
        
        $settings = apply_filters('tfl_posts_grid_' . $this->get_id() . '_settings', $settings);
        // Use the processed post selector query to find posts.
        $settings['query_type'] = 'custom_query';
        $settings['post_types'] = 'product';
        $settings['orderby'] = 'date';
        $settings['order'] = 'DESC';
        $settings['posts_per_page'] = 4;
        $query_args = tfl_build_query_args($settings);

        $query_args = apply_filters('tfl_posts_grid_' . $this->get_id() . '_query_args', $query_args, $settings);
        $loop = new \WP_Query($query_args);
        // Loop through the posts and do something with them.

        if ($loop->have_posts()) {
            $dir = (is_rtl() ? ' dir="rtl"' : '');
//            $target = ($settings['post_link_new_window'] == 'yes' ? ' target="_blank"' : '');
            // Check if any taxonomy filter has been applied
            list($chosen_terms, $taxonomies) = tfl_get_chosen_terms($query_args);

            $output = '<div class="tfl-portfolio-wrap tfl-gapless-grid">';


            $output .= '<div class="tfl-products"><div' . $dir . ' id="tfl-products-' . uniqid() . '" class="row tfl-' . esc_attr($settings['layout_mode']) . ' tfl-grid-container ' . 'tfl-' . tfl_get_grid_classes($settings) . '" data-isotope-options=\'{ "itemSelector": ".tfl-portfolio-item", "layoutMode": "' . esc_attr($settings['layout_mode']) . '", "originLeft": ' . esc_attr((!is_rtl() ? 'true' : 'false')) . '}\'>';
            $current_page = get_queried_object_id();
            while ($loop->have_posts()) {
                $loop->the_post();
                $post_id = get_the_ID();
                if ($post_id === $current_page) {
                    continue;
                }
                // skip current page since we can run into infinite loop when users choose All option in build query
                $style = '';
                foreach ($taxonomies as $taxonomy) {
                    $terms = get_the_terms($post_id, $taxonomy);
                    if (!empty($terms) && !is_wp_error($terms)) {
                        foreach ($terms as $term) {
                            $style .= ' term-' . $term->term_id;
                        }
                    }
                }
                $entry_output = '';
                $entry_output .= '<div id="post-' . $post_id . '" class="col-md-3 product-item ' . join(' ', get_post_class('', $post_id)) . '">';

                $entry_output .= '<div class="product-inner">';
                $thumbnail_exists = has_post_thumbnail();
                $entry_image = '<div class="wrap-thumb">';

                $image_setting = [
                    'id' => get_post_thumbnail_id($post_id),
                ];
                $thumbnail_html = tfl_get_image_html(
                    $image_setting,
                    'thumbnail_size',
                    $settings,
                    true
                );
                if ($settings['image_linkable'] == 'yes') {
                    $thumbnail_html = $thumbnail_html;
                }
                $entry_image .= apply_filters(
                    'tfl_posts_grid_thumbnail_html',
                    $thumbnail_html,
                    $image_setting,
                    $settings
                );
                $entry_image .= tfl_action_button();
                $entry_image .= '</div>';


                $image_info = '';
                $image_info .= '<a href="' . get_permalink() . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link"><h5 class="woocommerce-loop-product__title">' . get_the_title() . '</h5></a>';

                $image_info .= '<span class="price d-block text-center">';
                $_product = wc_get_product(get_the_ID());
                $image_info .= $_product->get_price_html();
                $image_info .= '</span>';

                $entry_image .= apply_filters(
                    'tfl_posts_grid_image_info',
                    $image_info,
                    $post_id,
                    $settings
                );

                $entry_output .= apply_filters(
                    'tfl_posts_grid_entry_image',
                    $entry_image,
                    $image_setting,
                    $settings
                );


                if ($settings['display_title'] == 'yes' || $settings['display_summary'] == 'yes') {
                    $entry_text = '<div class="tfl-entry-text-wrap ' . (($thumbnail_exists ? '' : ' nothumbnail')) . '">';


                    if ($settings['display_post_date'] == 'yes' || $settings['display_author'] == 'yes' || $settings['display_taxonomy'] == 'yes') {

                        $entry_meta = '<div class="tfl-entry-meta">';

                        $entry_meta .= '</div>';

                        $entry_text .= apply_filters(
                            'tfl_posts_grid_entry_meta',
                            $entry_meta,
                            $post_id,
                            $settings
                        );
                    }

                }


                $entry_output .= '</div><!-- .hentry -->';
                $entry_output .= '</div>';

                $output .= apply_filters(
                    'tfl_posts_grid_entry_output',
                    $entry_output,
                    $post_id,
                    $settings
                );
            }
            wp_reset_postdata();
            $output .= '</div><!-- .tfl-tfl-products -->';
            $output .= '</div><!-- .tfl-portfolio -->';
            $output .= '</div><!-- .tfl-portfolio-wrap -->';


            echo apply_filters('tfl_posts_grid_output', $output, $settings);
        }

    }

    protected function content_template()
    {
    }

}