<?php
if (!defined('ABSPATH')) {
    exit;
}
class United_Blog_Popular_Posts extends United_Blog_Widget_Base
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->widget_cssclass = 'widget_united_blog_popular_posts';
        $this->widget_description = __('Displays popular posts with an image', 'united-blog');
        $this->widget_id = 'united_blog_popular_posts';
        $this->widget_name = __('United Blog: Popular Posts', 'united-blog');
        $this->settings = array(
            'title' => array(
                'type' => 'text',
                'label' => __('Title', 'united-blog'),
            ),
            'post_settings_heading' => array(
                'type' => 'heading',
                'label' => __('Post Settings', 'united-blog'),
            ),
            'category' => 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'),
                ),
            ),
            'number' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 1,
                'max' => '',
                'std' => 5,
                'label' => __('Number of posts to show', 'united-blog'),
            ),
            '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'),
            ),
            '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'),
                ),
            ),
            'order' => array(
                'type' => 'select',
                'std' => 'desc',
                'label' => __('Order', 'united-blog'),
                'options' => array(
                    'asc' => __('ASC', 'united-blog'),
                    'desc' => __('DESC', 'united-blog'),
                ),
            ),
            'meta_settings_heading' => array(
                'type' => 'heading',
                'label' => __('Post Meta Settings', '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,
            ),
            'widget_settings_heading' => array(
                'type' => 'heading',
                'label' => __('Widget Settings', 'united-blog'),
            ),
            'post-content-alignment' => array(
                'type' => 'select',
                'label' => __('Content Vertical Alignment', 'united-blog'),
                'options' => array(
                    'card-alignment-top' => __('Vertical alignment top', 'united-blog'),
                    'card-alignment-space-between' => __('Vertical alignment space between', 'united-blog'),
                    'card-alignment-bottom' => __('Vertical alignment bottom', 'united-blog'),
                ),
                'std' => 'card-alignment-space-between',
            ),
            'enable_post_format_icon' => array(
                'type' => 'checkbox',
                'label' => __('Display Post Format Icon', 'united-blog'),
                'std' => true,
            ),
            'image_size' => array(
                'type' => 'select',
                'label' => __('Image size', 'united-blog'),
                'options' => array(
                    'medium' => __('Medium', 'united-blog'),
                    'medium_large' => __('Medium Large', 'united-blog'),
                    'large' => __('Large', 'united-blog'),
                    'full' => __('Full', 'united-blog'),
                ),
                'std' => 'medium_large',
            ),
            'height' => array(
                'type' => 'number',
                'step' => 1,
                'min' => 150,
                'max' => '',
                'std' => 560,
                'label' => __('Height (px)', 'united-blog'),
                'desc' => __('Change Height of Slides.', 'united-blog'),
            ),
            'bg_overlay_color' => array(
                'type' => 'color',
                'label' => __('Overlay Color', 'united-blog'),
                'std' => '#222',
            ),
            'overlay_opacity' => array(
                'type' => 'number',
                'step' => 10,
                'min' => 0,
                'max' => 100,
                'std' => 50,
                'label' => __('Overlay Opacity', 'united-blog'),
            ),
            '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'));
    }
    /**
     * Query the posts and return them.
     *
     * @param array $args
     * @param array $instance
     * @return WP_Query
     */
    public function get_posts($args, $instance)
    {
        $number = !empty($instance['number']) ? absint($instance['number']) : $this->settings['number']['std'];
        $orderby = !empty($instance['orderby']) ? sanitize_text_field($instance['orderby']) : $this->settings['orderby']['std'];
        $order = !empty($instance['order']) ? sanitize_text_field($instance['order']) : $this->settings['order']['std'];
        $offset = !empty($instance['offset']) ? sanitize_text_field($instance['offset']) : $this->settings['offset']['std'];
        $query_args = array(
            '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['category']) && -1 !== $instance['category'] && 0 !== $instance['category']) {
            $query_args['tax_query'][] = array(
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => $instance['category'],
            );
        }
        return new WP_Query(apply_filters('united_blog_popular_posts_query_args', $query_args));
    }
    /**
     * Output widget.
     *
     * @param array $args
     * @param array $instance
     * @see WP_Widget
     *
     */
    public function widget($args, $instance)
    {
        ob_start();
        if (($posts = $this->get_posts($args, $instance)) && $posts->have_posts()) {
            $this->widget_start($args, $instance);
            do_action('united_blog_before_popular_posts');
            $title_limit = isset($instance['title_limit']) ? $instance['title_limit'] : $this->settings['title_limit']['std'];
            $enabled_post_meta = isset($instance['post_meta']) ? $instance['post_meta'] : $this->settings['post_meta']['std'];
            $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'];
            ?>
            <div class="popular-posts-widget">
                <?php
                $counter = 1;

                $post_content_position = isset($instance['post-content-alignment']) ? $instance['post-content-alignment'] : $this->settings['post-content-alignment']['std'];
                $popular_post_class = $post_content_position;

                $enable_post_format_icon = isset($instance['enable_post_format_icon']) ? $instance['enable_post_format_icon'] : $this->settings['enable_post_format_icon']['std'];

                if ($enable_post_format_icon) {
                    $popular_post_class .= ' has-format-icon';
                }

                $image_size = !empty($instance['image_size']) ? $instance['image_size'] : $this->settings['image_size']['std'];
                $height = isset($instance['height']) ? $instance['height'] : $this->settings['height']['std'];
                $height = '--united-article-card-height:' . esc_attr($height) . 'px;';

                $bg_overlay_color = isset($instance['bg_overlay_color']) ? $instance['bg_overlay_color'] : $this->settings['bg_overlay_color']['std'];
                $overlay_opacity = isset($instance['overlay_opacity']) ? $instance['overlay_opacity'] : $this->settings['overlay_opacity']['std'];
                $style = 'background-color:' . $bg_overlay_color . ';';
                $style .= 'opacity:' . ($overlay_opacity / 100) . ';';
                while ($posts->have_posts()) :
                    $posts->the_post();
                    ?>
                    <article id="popular-post-<?php the_ID(); ?>" <?php post_class('united-article united-article-card has-space-bottom ' . esc_attr($popular_post_class)); ?> style="<?php echo esc_attr($height); ?>">
                        <?php if (has_post_thumbnail()) : ?>
                            <div class="entry-image">
                                <a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true" tabindex="-1">
                                    <span aria-hidden="true" class="united-article-overlay" style="<?php echo esc_attr($style); ?>"></span>
                                    <?php
                                    the_post_thumbnail(
                                        $image_size,
                                        array(
                                            'alt' => the_title_attribute(
                                                array(
                                                    'echo' => false,
                                                )
                                            ),
                                        )
                                    );
                                    ?>
                                </a>
                            </div>
                        <?php endif; ?>
                        <div class="entry-details">
                            <header class="entry-header">
                                <span class="article-counter"><?php echo esc_html($counter); ?></span>
                                <h3 class="entry-title entry-title-medium 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
                    ++$counter;
                endwhile;
                wp_reset_postdata();
                ?>
            </div>
            <?php
            do_action('united_blog_after_popular_posts');
            $this->widget_end($args);
        }
        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/popular-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);
            }
        }
    }
}
