<?php
/**
 * Blog Over Popular Posts Widget
 *
 * Displays popular posts based on comment count, date, or random.
 * Features thumbnails, post meta, and configurable layouts.
 *
 * @package Blog_Over
 * @since   1.0.0
 */

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

class Blog_Over_Popular_Posts_Widget extends WP_Widget
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct(
            'blog_over_popular_posts',
            esc_html__('Blog Over: Popular Posts', 'blog-over'),
            array(
                'description' => esc_html__('Displays popular posts with thumbnails.', 'blog-over'),
                'classname'   => 'blog-over-popular-posts-widget',
            )
        );
    }

    /**
     * Front-end display.
     *
     * @param array $args     Widget arguments.
     * @param array $instance Widget settings.
     */
    public function widget($args, $instance)
    {
        $title      = !empty($instance['title']) ? $instance['title'] : esc_html__('Popular Posts', 'blog-over');
        $title      = apply_filters('widget_title', $title, $instance, $this->id_base);
        $num_posts  = !empty($instance['num_posts']) ? absint($instance['num_posts']) : 5;
        $order_by   = !empty($instance['order_by']) ? $instance['order_by'] : 'comments';
        $show_thumb = isset($instance['show_thumb']) ? (bool) $instance['show_thumb'] : true;
        $show_date  = isset($instance['show_date']) ? (bool) $instance['show_date'] : true;
        $show_comments = isset($instance['show_comments']) ? (bool) $instance['show_comments'] : true;
        $layout     = !empty($instance['layout']) ? $instance['layout'] : 'list';

        // Build query args
        $query_args = array(
            'posts_per_page'      => $num_posts,
            'post_status'         => 'publish',
            'ignore_sticky_posts' => true,
            'no_found_rows'       => true,
        );

        switch ($order_by) {
            case 'comments':
                $query_args['orderby'] = 'comment_count';
                $query_args['order']   = 'DESC';
                break;
            case 'date':
                $query_args['orderby'] = 'date';
                $query_args['order']   = 'DESC';
                break;
            case 'random':
                $query_args['orderby'] = 'rand';
                break;
            case 'modified':
                $query_args['orderby'] = 'modified';
                $query_args['order']   = 'DESC';
                break;
        }

        $popular_posts = new WP_Query($query_args);

        if (!$popular_posts->have_posts()) {
            return;
        }

        echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

        if ($title) {
            echo $args['before_title'] . esc_html($title) . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }

        $layout_class = 'blog-over-popular-' . esc_attr($layout);
        echo '<div class="blog-over-popular-posts ' . esc_attr($layout_class) . '">';

        $counter = 1;
        while ($popular_posts->have_posts()) :
            $popular_posts->the_post();
            ?>
            <article class="blog-over-popular-post-item">
                <?php if ($layout === 'numbered') : ?>
                    <span class="blog-over-popular-number"><?php echo esc_html($counter); ?></span>
                <?php endif; ?>

                <?php if ($show_thumb && has_post_thumbnail()) : ?>
                    <div class="blog-over-popular-thumb">
                        <a href="<?php the_permalink(); ?>" aria-label="<?php the_title_attribute(); ?>">
                            <?php the_post_thumbnail('thumbnail', array('loading' => 'lazy')); ?>
                        </a>
                    </div>
                <?php endif; ?>

                <div class="blog-over-popular-content">
                    <h4 class="blog-over-popular-title">
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </h4>
                    <div class="blog-over-popular-meta">
                        <?php if ($show_date) : ?>
                            <span class="blog-over-popular-date">
                                <i class="far fa-clock" aria-hidden="true"></i>
                                <?php echo esc_html(get_the_date()); ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($show_comments) : ?>
                            <span class="blog-over-popular-comments">
                                <i class="far fa-comment" aria-hidden="true"></i>
                                <?php echo esc_html(get_comments_number()); ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </article>
            <?php
            $counter++;
        endwhile;

        echo '</div>';

        wp_reset_postdata();

        echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    /**
     * Widget admin form.
     *
     * @param array $instance Current settings.
     */
    public function form($instance)
    {
        $title         = !empty($instance['title']) ? $instance['title'] : esc_html__('Popular Posts', 'blog-over');
        $num_posts     = !empty($instance['num_posts']) ? absint($instance['num_posts']) : 5;
        $order_by      = !empty($instance['order_by']) ? $instance['order_by'] : 'comments';
        $show_thumb    = isset($instance['show_thumb']) ? (bool) $instance['show_thumb'] : true;
        $show_date     = isset($instance['show_date']) ? (bool) $instance['show_date'] : true;
        $show_comments = isset($instance['show_comments']) ? (bool) $instance['show_comments'] : true;
        $layout        = !empty($instance['layout']) ? $instance['layout'] : 'list';
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', 'blog-over'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text"
                   value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('num_posts')); ?>"><?php esc_html_e('Number of Posts:', 'blog-over'); ?></label>
            <input class="tiny-text" id="<?php echo esc_attr($this->get_field_id('num_posts')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('num_posts')); ?>" type="number"
                   min="1" max="20" value="<?php echo esc_attr($num_posts); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('order_by')); ?>"><?php esc_html_e('Order By:', 'blog-over'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('order_by')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('order_by')); ?>">
                <option value="comments" <?php selected($order_by, 'comments'); ?>><?php esc_html_e('Most Comments', 'blog-over'); ?></option>
                <option value="date" <?php selected($order_by, 'date'); ?>><?php esc_html_e('Most Recent', 'blog-over'); ?></option>
                <option value="modified" <?php selected($order_by, 'modified'); ?>><?php esc_html_e('Recently Updated', 'blog-over'); ?></option>
                <option value="random" <?php selected($order_by, 'random'); ?>><?php esc_html_e('Random', 'blog-over'); ?></option>
            </select>
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('layout')); ?>"><?php esc_html_e('Layout:', 'blog-over'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('layout')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('layout')); ?>">
                <option value="list" <?php selected($layout, 'list'); ?>><?php esc_html_e('List (Default)', 'blog-over'); ?></option>
                <option value="numbered" <?php selected($layout, 'numbered'); ?>><?php esc_html_e('Numbered List', 'blog-over'); ?></option>
                <option value="grid" <?php selected($layout, 'grid'); ?>><?php esc_html_e('Grid (2 Columns)', 'blog-over'); ?></option>
            </select>
        </p>
        <p>
            <input class="checkbox" type="checkbox" <?php checked($show_thumb); ?>
                   id="<?php echo esc_attr($this->get_field_id('show_thumb')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('show_thumb')); ?>">
            <label for="<?php echo esc_attr($this->get_field_id('show_thumb')); ?>"><?php esc_html_e('Show Thumbnail', 'blog-over'); ?></label>
        </p>
        <p>
            <input class="checkbox" type="checkbox" <?php checked($show_date); ?>
                   id="<?php echo esc_attr($this->get_field_id('show_date')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('show_date')); ?>">
            <label for="<?php echo esc_attr($this->get_field_id('show_date')); ?>"><?php esc_html_e('Show Date', 'blog-over'); ?></label>
        </p>
        <p>
            <input class="checkbox" type="checkbox" <?php checked($show_comments); ?>
                   id="<?php echo esc_attr($this->get_field_id('show_comments')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('show_comments')); ?>">
            <label for="<?php echo esc_attr($this->get_field_id('show_comments')); ?>"><?php esc_html_e('Show Comments Count', 'blog-over'); ?></label>
        </p>
        <?php
    }

    /**
     * Sanitize widget form values.
     *
     * @param array $new_instance New settings.
     * @param array $old_instance Previous settings.
     * @return array Sanitized settings.
     */
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title']         = sanitize_text_field($new_instance['title']);
        $instance['num_posts']     = absint($new_instance['num_posts']);
        $instance['order_by']      = sanitize_text_field($new_instance['order_by']);
        $instance['show_thumb']    = !empty($new_instance['show_thumb']);
        $instance['show_date']     = !empty($new_instance['show_date']);
        $instance['show_comments'] = !empty($new_instance['show_comments']);
        $instance['layout']        = sanitize_text_field($new_instance['layout']);
        return $instance;
    }
}

// Register the widget.
function blog_over_register_popular_posts_widget()
{
    register_widget('Blog_Over_Popular_Posts_Widget');
}
add_action('widgets_init', 'blog_over_register_popular_posts_widget');
