<?php 

class wrockmetro_Popular_Posts_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'wrockmetro_Popular_Posts_Widget',
            'Wrock Metro Popular Posts',
            array('description' => 'A widget to display popular posts with options.')
        );
    }

    public function widget($args, $instance) {
        $title = isset($instance['title']) ? $instance['title'] : 'Popular Posts';
        $category = isset($instance['category']) ? $instance['category'] : '';
        $show_featured_image = isset($instance['show_featured_image']) ? $instance['show_featured_image'] : true;
        $show_view_counts = isset($instance['show_view_counts']) ? $instance['show_view_counts'] : true;
        $num_posts = isset($instance['num_posts']) ? $instance['num_posts'] : 5;
        $sort_by_views = isset($instance['sort_by_views']) ? $instance['sort_by_views'] : false;

        $args_query = array(
		'ignore_sticky_posts' => true,
            'posts_per_page' => $num_posts,
            'orderby' => $sort_by_views ? 'meta_value_num' : 'comment_count', // Always sort by views for popular posts
            'meta_key' => '_post_views_count',
        );

        if (!empty($category) && $category !== 'all') {
            $args_query['category_name'] = $category;
        }

        $popular_posts_query = new WP_Query($args_query);

        echo '<div class="wrockmetro-popular">';
        echo '<h2 class="wp-block-heading">'. apply_filters('widget_title', $title) .'</h2>';

        if ($popular_posts_query->have_posts()) {
            echo '<ul>';
            while ($popular_posts_query->have_posts()) {
                $popular_posts_query->the_post();
                ?>
                <li>
                    <a href="<?php the_permalink(); ?>">
                    <?php if ($show_featured_image && has_post_thumbnail()) : ?>
                        <div class="post-thumbnail">
                            <?php the_post_thumbnail(array(70, 70)); ?>
                        </div>
                    <?php endif; ?><?php the_title(); ?></a>
                    <?php if ($show_view_counts) : ?>
                        <?php display_post_view_count(); ?>
                    <?php endif; ?>
                </li>
                <?php
            }
            echo '</ul>';
            wp_reset_postdata();
        }
        echo "</div>";
    }

    public function form($instance) {
        $title = isset($instance['title']) ? $instance['title'] : 'Popular Posts';
        $category = isset($instance['category']) ? $instance['category'] : '';
        $show_featured_image = isset($instance['show_featured_image']) ? $instance['show_featured_image'] : true;
        $sort_by_views = isset($instance['sort_by_views']) ? $instance['sort_by_views'] : false;
        $show_view_counts = isset($instance['show_view_counts']) ? $instance['show_view_counts'] : true;
        $num_posts = isset($instance['num_posts']) ? $instance['num_posts'] : 5;
        ?>
        <p>
           <label for="<?php echo $this->get_field_id('title'); ?>">Widget Title:</label>
           <input type="text" 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('category'); ?>">Choose Category:</label>
            <?php
            $categories = get_categories(array('hide_empty' => 0));
            ?>
            <select id="<?php echo $this->get_field_id('category'); ?>"
                    name="<?php echo $this->get_field_name('category'); ?>">
                <option value="all"<?php selected($category, 'all'); ?>>All Categories</option>
                <?php foreach ($categories as $cat) : ?>
                    <option value="<?php echo esc_attr($cat->slug); ?>" <?php selected($category, $cat->slug); ?>><?php echo esc_html($cat->name); ?></option>
                <?php endforeach; ?>
            </select>
        </p>
        <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_featured_image'); ?>"
                   name="<?php echo $this->get_field_name('show_featured_image'); ?>" <?php checked($show_featured_image, true); ?>>
            <label for="<?php echo $this->get_field_id('show_featured_image'); ?>">Show Featured Image</label>
        </p>
        <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_view_counts'); ?>"
                   name="<?php echo $this->get_field_name('show_view_counts'); ?>" <?php checked($show_view_counts, true); ?>>
            <label for="<?php echo $this->get_field_id('show_view_counts'); ?>">Show View Counts</label>
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('num_posts'); ?>">Number of Popular Posts to Display:</label>
            <input type="number" id="<?php echo $this->get_field_id('num_posts'); ?>"
                   name="<?php echo $this->get_field_name('num_posts'); ?>" value="<?php echo $num_posts; ?>">
        </p>
        <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('sort_by_views'); ?>"
                   name="<?php echo $this->get_field_name('sort_by_views'); ?>" <?php checked($sort_by_views, true); ?>>
            <label for="<?php echo $this->get_field_id('sort_by_views'); ?>">Sort by Views</label>
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : 'Popular Posts';
        $instance['category'] = !empty($new_instance['category']) ? sanitize_text_field($new_instance['category']) : 'all';
        $instance['show_featured_image'] = isset($new_instance['show_featured_image']) ? true : false;
        $instance['show_view_counts'] = isset($new_instance['show_view_counts']) ? true : false;
        $instance['num_posts'] = !empty($new_instance['num_posts']) ? intval($new_instance['num_posts']) : 5;
        $instance['sort_by_views'] = isset($new_instance['sort_by_views']) ? true : false;
        return $instance;
    }
}

function register_wrockmetro_Popular_Posts_Widget() {
    register_widget('wrockmetro_Popular_Posts_Widget');
}
add_action('widgets_init', 'register_wrockmetro_Popular_Posts_Widget');
