<?php

/*
Widget Name: Posts Grid
Description: Display posts or custom post types in a multi-column grid.
Author: ThemesFlat
Author URI: https://www.themesflatthemes.com
*/
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_Posts_Widget extends TFL_Widget_Base
{
    public function get_name()
    {
        return 'tfl-posts';
    }
    
    public function get_title()
    {
        return __( 'Posts Grid', 'themesflat' );
    }
    
    public function get_icon()
    {
        return 'tfl-icon-posts-grid-masonry';
    }
    
    public function get_categories()
    {
        return array( 'themesflat-addons' );
    }
    
    public function get_custom_help_url()
    {
        return 'https://themesflatelementor.com/docs/themesflat-addons/core-addons/posts-grid/';
    }
    
    public function get_script_depends()
    {
        return [
            'isotope.pkgd',
            'imagesloaded.pkgd',
            'tfl-frontend-scripts'
        ];
    }
    
    public function get_style_depends()
    {
        return [ 'tfl-frontend-styles', 'tfl-grid-styles' ];
    }
    
    protected function register_controls()
    {
        $this->start_controls_section( 'section_query', [
            'label' => __( 'Post Query', 'themesflat' ),
        ] );
        $this->add_control( 'query_type', [
            'label'   => __( 'Source', 'themesflat' ),
            'type'    => Controls_Manager::SELECT,
            'options' => array(
            'custom_query'  => __( 'Custom Query', 'themesflat' ),
        ),
            'default' => 'custom_query',
        ] );

        $this->add_control( 'post_in', [
            'label'       => __( 'Post In', 'themesflat' ),
            'description' => __( 'Provide a comma separated list of Post IDs to display in the grid.', 'themesflat' ),
            'type'        => Controls_Manager::TEXT,
            'label_block' => true,
            'condition'   => [
            'query_type' => 'custom_query',
        ],
        ] );
        $this->add_control( 'posts_per_page', [
            'label'     => __( 'Posts Per Page', 'themesflat' ),
            'type'      => Controls_Manager::NUMBER,
            'min'       => 1,
            'max'       => 50,
            'step'      => 1,
            'default'   => 6,
            'condition' => [
            'query_type' => [ 'custom_query', 'related' ],
        ],
        ] );
        $this->add_control( 'advanced', [
            'label'     => __( 'Advanced', 'themesflat' ),
            'type'      => Controls_Manager::HEADING,
            'condition' => [
            'query_type' => [ 'custom_query', 'related' ],
        ],
        ] );
        $this->add_control( 'orderby', [
            'label'     => __( 'Order By', 'themesflat' ),
            'type'      => Controls_Manager::SELECT,
            'options'   => array(
            'none'          => __( 'No order', 'themesflat' ),
            'ID'            => __( 'Post ID', 'themesflat' ),
            'author'        => __( 'Author', 'themesflat' ),
            'title'         => __( 'Title', 'themesflat' ),
            'date'          => __( 'Published date', 'themesflat' ),
            'modified'      => __( 'Modified date', 'themesflat' ),
            'parent'        => __( 'By parent', 'themesflat' ),
            'rand'          => __( 'Random order', 'themesflat' ),
            'comment_count' => __( 'Comment count', 'themesflat' ),
            'menu_order'    => __( 'Menu order', 'themesflat' ),
            'post__in'      => __( 'By include order', 'themesflat' ),
        ),
            'default'   => 'date',
            'condition' => [
            'query_type' => [ 'custom_query', 'related' ],
        ],
        ] );
        $this->add_control( 'order', [
            'label'     => __( 'Order', 'themesflat' ),
            'type'      => Controls_Manager::SELECT,
            'options'   => array(
            'ASC'  => __( 'Ascending', 'themesflat' ),
            'DESC' => __( 'Descending', 'themesflat' ),
        ),
            'default'   => 'DESC',
            'condition' => [
            'query_type' => [ 'custom_query', 'related' ],
        ],
        ] );
        $this->add_control( 'offset', [
            'label'       => __( 'Offset', 'themesflat' ),
            'description' => __( 'Number of posts to skip or pass over.', 'themesflat' ),
            'type'        => Controls_Manager::NUMBER,
            'default'     => 0,
            'condition'   => [
            'query_type' => 'custom_query',
        ],
        ] );

        $this->end_controls_section();


        $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->add_control( 'image_linkable', [
            'label'        => __( 'Link Images to Posts?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'post_link_new_window', [
            'label'        => __( 'Open post links in new window?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => '',
        ] );
        $this->add_control( 'display_title_on_thumbnail', [
            'label'        => __( 'Display posts title on the post thumbnail?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_taxonomy_on_thumbnail', [
            'label'        => __( 'Display taxonomy info on post/project thumbnail?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_title', [
            'label'        => __( 'Display posts title for the post item?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_summary', [
            'label'        => __( 'Display post excerpt/summary for the post item?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_author', [
            'label'        => __( 'Display post author info for the post item?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_post_date', [
            'label'        => __( 'Display post date info for the post item?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_taxonomy', [
            'label'        => __( 'Display taxonomy info for the post item?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'yes',
        ] );
        $this->add_control( 'display_read_more', [
            'label'        => __( 'Display read more link to the post?', 'themesflat' ),
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => __( 'Yes', 'themesflat' ),
            'label_off'    => __( 'No', 'themesflat' ),
            'return_value' => 'yes',
            'default'      => 'no',
        ] );
        $this->add_control( 'read_more_text', [
            'label'       => __( 'Read more text', 'themesflat' ),
            'type'        => Controls_Manager::TEXT,
            "description" => __( 'Specify the text for the read more link/button', 'themesflat' ),
            'default'     => __( 'Read More', 'themesflat' ),
            'condition'   => [
            'display_read_more' => [ 'yes' ],
        ],
        ] );
        $this->end_controls_section();
        $this->start_controls_section( 'section_general_settings', [
            'label' => __( 'General', 'themesflat' ),
            'tab'   => Controls_Manager::TAB_SETTINGS,
        ] );


        $this->add_control( 'style', [
            'type'    => Controls_Manager::SELECT,
            'label'   => __( 'Style', 'themesflat' ),
            'options' => array(
                'style1' => __( 'Style 1', 'themesflat' ),
                'style2' => __( 'Style 2', 'themesflat' ),
                'style3' => __( 'Style 3', 'themesflat' ),
            ),
            'default' => 'style1',
        ] );

        $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['layout_mode'] = 'fitRows';
        $settings['per_line'] = 3;
        $settings['per_line_tablet'] = 2;
        $settings['per_line_mobile'] = 1;
        $settings['title_tag'] = 'h5';

        $settings = apply_filters( 'tfl_posts_grid_' . $this->get_id() . '_settings', $settings );
        // Use the processed post selector query to find posts.
        $query_args = tfl_build_query_args( $settings );
        $query_args = apply_filters( 'tfl_posts_grid_' . $this->get_id() . '_query_args', $query_args, $settings );
        $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 );


            echo '<div class="tfl-posts-wrap tfl-gapless-grid tfl-'.$settings['style'].'">';
                echo '<div' . $dir . ' id="tfl-posts-' . uniqid() . '" class="row tfl-' . esc_attr( $settings['layout_mode'] ) . ' tfl-grid-container ' . 'tfl-'  . tfl_get_grid_classes( $settings ) . '" data-isotope-options=\'{ "itemSelector": ".tfl-posts-item", "layoutMode": "' . esc_attr( $settings['layout_mode'] ) . '", "originLeft": ' . esc_attr( ( !is_rtl() ? 'true' : 'false' ) ) . '}\'>';
                $current_page = get_queried_object_id();

                $entry_output = '';
                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;
                            }
                        }
                    }

                    $args['post_id'] =  $post_id;
                    $args['settings'] =  $settings;
                    $args['target'] =  $target;

                    tfl_get_template_part("addons/post-grid/".$settings['style'], $args);
                }
                wp_reset_postdata();
                echo '</div></div>';

        }
    
    }
    
    protected function content_template()
    {
    }

}