<?php
if (!defined('ABSPATH')) {
    exit;
}
class United_Blog_Tab_Posts extends United_Blog_Widget_Base
{
    public $display_style = '';
    public $unique_id;
    private static $counter = 0;
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->widget_cssclass = 'united_blog_widget_tab_posts';
        $this->widget_description = __('Displays posts in tab', 'united-blog');
        $this->widget_id = 'united_blog_tab_posts';
        $this->widget_name = __('United Blog: Tab Posts', 'united-blog');
        $this->settings = array(
            'popular_post_settings' => array(
                'type' => 'heading',
                'label' => __('Popular Post Settings', 'united-blog'),
            ),
            'show_popular_posts' => array(
                'type' => 'checkbox',
                'label' => __('Show Tab', 'united-blog'),
                'std' => true,
            ),
            'popular_posts_title' => array(
                'type' => 'text',
                'label' => __('Title', 'united-blog'),
                'std' => __('Popular', 'united-blog'),
                'desc' => __('Leave as it is to show default title or leave blank to only show icon', 'united-blog'),
            ),
            'popular_post_cat' => array(
                'type' => 'dropdown-taxonomies',
                'label' => __('Select Category', 'united-blog'),
                'desc' => __('Leave empty if you don\'t want the posts to be category specific', 'united-blog'),
                'args' => array(
                    'taxonomy' => 'category',
                    'class' => 'widefat',
                    'hierarchical' => true,
                    'show_count' => 1,
                    'show_option_all' => __('&mdash; Select &mdash;', 'united-blog'),
                ),
            ),
            'popular_post_offset' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 0,
                'max' => '',
                'std' => '',
                'label' => __('Offset', 'united-blog'),
                'desc' => __('Can be useful if you want to skip certain number of posts. Leave as 0 if you do not want to use it.', 'united-blog'),
            ),
            'popular_post_orderby' => array(
                'type' => 'select',
                'std' => 'comment_count',
                'label' => __('Order By', 'united-blog'),
                'options' => array(
                    'date' => __('Date', 'united-blog'),
                    'ID' => __('ID', 'united-blog'),
                    'title' => __('Title', 'united-blog'),
                    'rand' => __('Random', 'united-blog'),
                    'comment_count' => __('Comment Count', 'united-blog'),
                ),
            ),
            'popular_post_order' => array(
                'type' => 'select',
                'std' => 'desc',
                'label' => __('Order', 'united-blog'),
                'options' => array(
                    'asc' => __('ASC', 'united-blog'),
                    'desc' => __('DESC', 'united-blog'),
                ),
            ),
            'hot_post_settings' => array(
                'type' => 'heading',
                'label' => __('Hot Post Settings', 'united-blog'),
            ),
            'show_hot_posts' => array(
                'type' => 'checkbox',
                'label' => __('Show Tab', 'united-blog'),
                'std' => false,
            ),
            'hot_posts_title' => array(
                'type' => 'text',
                'label' => __('Title', 'united-blog'),
                'std' => __('Hot', 'united-blog'),
                'desc' => __('Leave as it is to show default title or leave blank to only show icon', 'united-blog'),
            ),
            'hot_post_cat' => array(
                'type' => 'dropdown-taxonomies',
                'label' => __('Select Category', 'united-blog'),
                'desc' => __('Leave empty if you don\'t want the posts to be category specific', 'united-blog'),
                'args' => array(
                    'taxonomy' => 'category',
                    'class' => 'widefat',
                    'hierarchical' => true,
                    'show_count' => 1,
                    'show_option_all' => __('&mdash; Select &mdash;', 'united-blog'),
                ),
            ),
            'hot_post_offset' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 0,
                'max' => '',
                'std' => '',
                'label' => __('Offset', 'united-blog'),
                'desc' => __('Can be useful if you want to skip certain number of posts. Leave as 0 if you do not want to use it.', 'united-blog'),
            ),
            'hot_post_orderby' => array(
                'type' => 'select',
                'std' => 'date',
                'label' => __('Order By', 'united-blog'),
                'options' => array(
                    'date' => __('Date', 'united-blog'),
                    'ID' => __('ID', 'united-blog'),
                    'title' => __('Title', 'united-blog'),
                    'rand' => __('Random', 'united-blog'),
                    'comment_count' => __('Comment Count', 'united-blog'),
                ),
            ),
            'hot_post_order' => array(
                'type' => 'select',
                'std' => 'desc',
                'label' => __('Order', 'united-blog'),
                'options' => array(
                    'asc' => __('ASC', 'united-blog'),
                    'desc' => __('DESC', 'united-blog'),
                ),
            ),
            'latest_post_settings' => array(
                'type' => 'heading',
                'label' => __('Latest Post Settings', 'united-blog'),
            ),
            'show_latest_posts' => array(
                'type' => 'checkbox',
                'label' => __('Show Tab', 'united-blog'),
                'std' => true,
            ),
            'latest_posts_title' => array(
                'type' => 'text',
                'label' => __('Title', 'united-blog'),
                'std' => __('Latest', 'united-blog'),
                'desc' => __('Leave as it is to show default title or leave blank to only show icon', 'united-blog'),
            ),
            'latest_post_cat' => array(
                'type' => 'dropdown-taxonomies',
                'label' => __('Select Category', 'united-blog'),
                'desc' => __('Leave empty if you don\'t want the posts to be category specific', 'united-blog'),
                'args' => array(
                    'taxonomy' => 'category',
                    'class' => 'widefat',
                    'hierarchical' => true,
                    'show_count' => 1,
                    'show_option_all' => __('&mdash; Select &mdash;', 'united-blog'),
                ),
            ),
            'latest_post_offset' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 0,
                'max' => '',
                'std' => '',
                'label' => __('Offset', 'united-blog'),
                'desc' => __('Can be useful if you want to skip certain number of posts. Leave as 0 if you do not want to use it.', 'united-blog'),
            ),
            'latest_post_orderby' => array(
                'type' => 'select',
                'std' => 'date',
                'label' => __('Order By', 'united-blog'),
                'options' => array(
                    'date' => __('Date', 'united-blog'),
                    'ID' => __('ID', 'united-blog'),
                    'title' => __('Title', 'united-blog'),
                    'rand' => __('Random', 'united-blog'),
                    'comment_count' => __('Comment Count', 'united-blog'),
                ),
            ),
            'latest_post_order' => array(
                'type' => 'select',
                'std' => 'desc',
                'label' => __('Order', 'united-blog'),
                'options' => array(
                    'asc' => __('ASC', 'united-blog'),
                    'desc' => __('DESC', 'united-blog'),
                ),
            ),
            'comments_settings' => array(
                'type' => 'heading',
                'label' => __('Comments Settings', 'united-blog'),
            ),
            'show_comment_tab' => array(
                'type' => 'checkbox',
                'label' => __('Show Tab', 'united-blog'),
                'std' => false,
            ),
            'comments_title' => array(
                'type' => 'text',
                'label' => __('Title', 'united-blog'),
                'std' => __('Comments', 'united-blog'),
                'desc' => __('Leave as it is to show default title or leave blank to only show icon', 'united-blog'),
            ),
            'comments_number' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 1,
                'max' => '',
                'std' => 5,
                'label' => __('Number of comments to show', 'united-blog'),
            ),
            'show_comment_user_img' => array(
                'type' => 'checkbox',
                'label' => __('Show Comment Avatar', 'united-blog'),
                'std' => true,
            ),
            'show_comment_date' => array(
                'type' => 'checkbox',
                'label' => __('Show Comment Date', 'united-blog'),
                'std' => true,
            ),
            'show_comment_excerpt' => array(
                'type' => 'checkbox',
                'label' => __('Show Comment Excerpt', 'united-blog'),
                'std' => true,
            ),
            'general_settings' => array(
                'type' => 'heading',
                'label' => __('General Settings', 'united-blog'),
            ),
            'Select_posts_header' => array(
                'type' => 'select',
                'std' => 'title',
                'label' => __('Select Title As', 'united-blog'),
                'options' => array(
                    'icon' => __('Icon Only', 'united-blog'),
                    'title' => __('Title Only', 'united-blog'),
                ),
            ),
            'number' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 1,
                'max' => '',
                'std' => 3,
                'label' => __('Number of posts to show', 'united-blog'),
            ),
            'post_meta' => array(
                'type' => 'multi-checkbox',
                'label' => __('Post Meta', 'united-blog'),
                'options' => array(
                    'author' => __('Author', 'united-blog'),
                    'date' => __('Date', 'united-blog'),
                    'comment' => __('Comment', 'united-blog'),
                ),
                'std' => array('date'),
            ),
            'date_format' => array(
                'type' => 'select',
                'label' => __('Date Format', 'united-blog'),
                'desc' => __('Make sure to select Date from above for this to work.', 'united-blog'),
                'options' => array(
                    'format_1' => __('Times Ago', 'united-blog'),
                    'format_2' => __('Default Format', 'united-blog'),
                ),
                'std' => 'format_1',
            ),
            'author_image' => array(
                'type' => 'checkbox',
                'label' => __('Show Author Image', 'united-blog'),
                'desc' => __('Make sure to select Author from above for this to work.', 'united-blog'),
                'std' => false,
            ),
            'show_category' => array(
                'type' => 'checkbox',
                'label' => __('Show Category', 'united-blog'),
                'std' => true,
            ),
            'category_color' => array(
                'type' => 'select',
                'label' => __('Categories Display Style', 'united-blog'),
                'options' => united_blog_get_category_display_styles(),
                'std' => 'none',
            ),
            'no_of_category' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 0,
                'max' => '',
                'std' => 1,
                'label' => __('Number of Categories to Display', 'united-blog'),
            ),
            'invert_post' => array(
                'type' => 'checkbox',
                'label' => __('Invert Post', 'united-blog'),
                'std' => false,
            ),
            'hide_image' => array(
                'type' => 'checkbox',
                'label' => __('Hide Post Image', 'united-blog'),
                'std' => false,
            ),
            'featured_image_style' => array(
                'type' => 'checkbox',
                'label' => __('Display Circular Featured Image', 'united-blog'),
                'std' => true,
            ),
            'enable_post_format_icon' => array(
                'type' => 'checkbox',
                'label' => __('Display Post Format Icon', 'united-blog'),
                'std' => true,
            ),
            'title_limit' => array(
                'type' => 'select',
                'label' => __('Post Title Limit', 'united-blog'),
                'options' => united_blog_get_title_line_clamp(),
                'std' => '',
            ),
        );
        parent::__construct();
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
    }
    /**
     * Outputs the tab Content
     *
     * @param array $instance
     * @param string $block The block to display.
     */
    public function render_tab_title($instance, $block, $is_active = false)
    {
        if (!$block) {
            return;
        }
        $enabled = isset($instance["show_{$block}_posts"]) ? $instance["show_{$block}_posts"] : $this->settings["show_{$block}_posts"]['std'];
        if ($enabled) :
            $icon = isset($instance["Select_posts_header"]) ? $instance["Select_posts_header"] : $this->settings["Select_posts_header"]['std'];
            $title = isset($instance["{$block}_posts_title"]) ? $instance["{$block}_posts_title"] : $this->settings["{$block}_posts_title"]['std'];
            ?>
            <a id="<?php echo esc_attr($block); ?>-posts-<?php echo esc_attr($this->unique_id); ?>"
               href="#<?php echo esc_attr($block); ?>-posts-<?php echo esc_attr($this->unique_id); ?>-block"
               class="tab-item tab-link<?php echo ($is_active) ? ' active' : ''; ?>" data-toggle="united-data-tab"
               aria-selected="<?php echo ($is_active) ? 'true' : 'false'; ?>" role="tab"
               aria-controls="<?php echo esc_attr($block); ?>-posts-<?php echo esc_attr($this->unique_id); ?>-block">
                <?php if ($icon === 'icon') : ?>
                    <span class="tab-title-icon"><?php united_blog_the_theme_svg($block); ?></span>
                <?php endif; ?>
                <?php if ($title && $icon === 'title') : ?>
                    <span class="tab-title-label"><?php echo esc_html($title); ?></span>
                <?php endif; ?>
            </a>
        <?php
        endif;

    }
    /**
     * Outputs the tab Content
     *
     * @param array $instance
     * @param string $block The block to display.
     */
    public function render_tab_content($instance, $block, $is_active = false)
    {
        if (!$block) {
            return;
        }
        $enabled = isset($instance["show_{$block}_posts"]) ? $instance["show_{$block}_posts"] : $this->settings["show_{$block}_posts"]['std'];
        $hide_image = isset($instance['hide_image']) ? $instance['hide_image'] : $this->settings['hide_image']['std'];
        $title_limit = isset($instance['title_limit']) ? $instance['title_limit'] : $this->settings['title_limit']['std'];
        $enable_post_format_icon = isset($instance['enable_post_format_icon']) ? $instance['enable_post_format_icon'] : $this->settings['enable_post_format_icon']['std'];
        $featured_image_style = isset($instance['featured_image_style']) ? $instance['featured_image_style'] : $this->settings['featured_image_style']['std'];
        if ($enabled) :
            $number = !empty($instance['number']) ? absint($instance['number']) : $this->settings['number']['std'];
            $orderby = !empty($instance["{$block}_post_orderby"]) ? sanitize_text_field($instance["{$block}_post_orderby"]) : $this->settings["{$block}_post_orderby"]['std'];
            $order = !empty($instance["{$block}_post_order"]) ? sanitize_text_field($instance["{$block}_post_order"]) : $this->settings["{$block}_post_order"]['std'];
            $offset = !empty($instance["{$block}_post_offset"]) ? sanitize_text_field($instance["{$block}_post_offset"]) : $this->settings["{$block}_post_offset"]['std'];
            $query_args = array(
                'post_type' => 'post',
                'posts_per_page' => $number,
                'post_status' => 'publish',
                'no_found_rows' => 1,
                'orderby' => $orderby,
                'order' => $order,
                'ignore_sticky_posts' => 1,
            );
            if ($offset && 0 != $offset) {
                $query_args['offset'] = absint($offset);
            }
            if (!empty($instance["{$block}_post_cat"]) && -1 != $instance["{$block}_post_cat"] && 0 != $instance["{$block}_post_cat"]) {
                $query_args['tax_query'][] = array(
                    'taxonomy' => 'category',
                    'field' => 'term_id',
                    'terms' => $instance["{$block}_post_cat"],
                );
            }
            $posts = new WP_Query($query_args);
            if ($posts->have_posts()) :
                $enabled_post_meta = isset($instance['post_meta']) ? $instance['post_meta'] : $this->settings['post_meta']['std'];
                $invert_post = isset($instance['invert_post']) ? $instance['invert_post'] : $this->settings['invert_post']['std'];
                $tabbed_post_class = $this->display_style;
                if ($invert_post) {
                    $tabbed_post_class .= ' is-list-reverse';
                }
                $meta_settings['date_format'] = isset($instance['date_format']) ? $instance['date_format'] : $this->settings['date_format']['std'];
                $meta_settings['author_image'] = isset($instance['author_image']) ? $instance['author_image'] : $this->settings['author_image']['std'];
                $show_category = isset($instance['show_category']) ? $instance['show_category'] : $this->settings['show_category']['std'];
                if ($show_category) {
                    $color = isset($instance['category_color']) ? $instance['category_color'] : $this->settings['category_color']['std'];
                    $limit = isset($instance['no_of_category']) ? $instance['no_of_category'] : $this->settings['no_of_category']['std'];
                }
                if ($enable_post_format_icon) {
                    $tabbed_post_class .= ' has-format-icon';
                }
                if ($featured_image_style) {
                    
                    $tabbed_post_class .= ' has-round-image';
                }
                ?>
                <div id="<?php echo esc_attr($block); ?>-posts-<?php echo esc_attr($this->unique_id); ?>-block" class="tabbed-content-panel <?php echo ($is_active) ? 'active' : ''; ?>" role="tabpanel" aria-labelledby="<?php echo esc_attr($block); ?>-posts-<?php echo esc_attr($this->unique_id); ?>">
                    <?php
                    while ($posts->have_posts()) :
                        $posts->the_post();
                        ?>
                        <article id="tabbed-post-<?php the_ID(); ?>" <?php post_class('united-article united-article-list has-space-bottom has-border-bottom ' . esc_attr($tabbed_post_class)); ?>>
                            <?php
                            if (!$hide_image && has_post_thumbnail()) {
                                ?>
                                <div class="entry-image entry-image-thumbnail">
                                    <a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true"
                                       tabindex="-1">
                                        <?php
                                        the_post_thumbnail(
                                            'medium',
                                            array(
                                                'alt' => the_title_attribute(
                                                    array(
                                                        'echo' => false,
                                                    )
                                                ),
                                            )
                                        );
                                        ?>
                                    </a>
                                </div>
                            <?php } ?>
                            <div class="entry-details">
                                <?php
                                if ($show_category) {
                                    united_blog_post_categories($color, $limit);
                                }
                                ?>
                                <header class="entry-header">
                                    <h3 class="entry-title entry-title-small has-line-clamp <?php echo esc_attr($title_limit); ?>">
                                        <a href="<?php echo esc_url(get_permalink()); ?>" rel="bookmark">
                                            <?php the_title(); ?>
                                        </a>
                                    </h3>
                                </header>
                                <?php united_blog_post_meta_info($enabled_post_meta, $meta_settings); ?>
                            </div>
                        </article>
                    <?php
                    endwhile;
                    wp_reset_postdata();
                    ?>
                </div>
            <?php
            endif;
        endif;
    }
    /**
     * Output widget.
     *
     * @param array $args
     * @param array $instance
     * @see WP_Widget
     *
     */
    public function widget($args, $instance)
    {
        ob_start();
        $before_widget = $args['before_widget'];
        $after_widget = $args['after_widget'];
        echo wp_kses_post($before_widget);
        do_action('united_blog_before_tab_posts');
        // Comments Tab.
        if (function_exists('has_blocks')) {
            $is_gutenberg = true;
        } else {
            $is_gutenberg = false;
        }
        $show_comment_tab = isset($instance['show_comment_tab']) ? $instance['show_comment_tab'] : $this->settings['show_comment_tab']['std'];
        ++self::$counter;
        $this->unique_id = 'united-tab-' . self::$counter;
        ?>
        <div class="tabbed-posts-widget">
            <div class="tabbed-widget-header" role="tablist"
                 aria-label="<?php esc_attr_e('Tab Navigation', 'united-blog'); ?>">
                <?php $this->render_tab_title($instance, 'popular', true); ?>
                <?php $this->render_tab_title($instance, 'hot'); ?>
                <?php $this->render_tab_title($instance, 'latest'); ?>
                <?php
                if ($is_gutenberg && $show_comment_tab) :
                    $show_comments_icon = isset($instance["Select_posts_header"]) ? $instance["Select_posts_header"] : $this->settings["Select_posts_header"]['std'];
                    $comments_title = isset($instance['comments_title']) ? $instance['comments_title'] : $this->settings['comments_title']['std'];
                    ?>
                    <a id="latest-comments-<?php echo esc_attr($this->unique_id); ?>"
                       href="#latest-comments-<?php echo esc_attr($this->unique_id); ?>-block"
                       class="tab-item tab-link" data-toggle="united-data-tab" aria-selected="false" role="tab"
                       aria-controls="latest-comments-<?php echo esc_attr($this->unique_id); ?>-block">

                       <?php if ($show_comments_icon === 'icon') : ?>
                            <span class="tab-title-icon"><?php united_blog_the_theme_svg('commented'); ?></span>
                       <?php endif; ?>
                       <?php if ($comments_title && $show_comments_icon === 'title') : ?>
                            <span class="tab-title-label"><?php echo $comments_title; ?></span>
                       <?php endif; ?>
                    </a>
                <?php endif; ?>
            </div>
            <div class="tabbed-widget-content">
                <?php $this->render_tab_content($instance, 'popular', true); ?>
                <?php $this->render_tab_content($instance, 'hot'); ?>
                <?php $this->render_tab_content($instance, 'latest'); ?>
                <?php
                if ($is_gutenberg && $show_comment_tab) :
                    // Build attributes.
                    $comments_number = isset($instance['comments_number']) ? $instance['comments_number'] : $this->settings['comments_number']['std'];
                    $show_comment_user_img = isset($instance['show_comment_user_img']) ? $instance['show_comment_user_img'] : $this->settings['show_comment_user_img']['std'];
                    $show_comment_date = isset($instance['show_comment_date']) ? $instance['show_comment_date'] : $this->settings['show_comment_date']['std'];
                    $show_comment_excerpt = isset($instance['show_comment_excerpt']) ? $instance['show_comment_excerpt'] : $this->settings['show_comment_excerpt']['std'];
                    ?>
                    <div id="latest-comments-<?php echo esc_attr($this->unique_id); ?>-block" class="tabbed-content-panel" role="tabpanel" aria-labelledby="latest-comments-<?php echo esc_attr($this->unique_id); ?>">
                        <?php
                        $blocks = parse_blocks('<!-- wp:latest-comments {"commentsToShow":' . absint($comments_number) . ',"displayAvatar":' . $show_comment_user_img . ',"displayDate":' . $show_comment_date . ',"displayExcerpt":' . $show_comment_excerpt . '} /-->');
                        foreach ($blocks as $block) {
                            echo render_block($block);
                        }
                        ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        do_action('united_blog_after_tab_posts');
        echo wp_kses_post($after_widget);
        echo ob_get_clean();
    }
    public function enqueue_assets()
    {
        if (is_active_widget(false, false, $this->id_base)) {
            $file_prefix = is_rtl() ? '-rtl' : '';
            $css_file = get_template_directory() . '/inc/widgets/css/tab-posts' . $file_prefix . '.css';
            if (file_exists($css_file)) {
                $styles = wp_strip_all_tags(file_get_contents($css_file));
                wp_add_inline_style('united-blog-style', $styles);
            }
        }
    }
}
