<?php
/**
 * Blog Sidebar Template Part
 *
 * @package shopbar
 */
?>

<aside class="blog-sidebar sidebar" aria-label="<?php esc_attr_e( 'Blog sidebar', 'shopbar' ); ?>">

    <!-- Search -->
    <div class="blog-sidebar-search">
        <?php get_search_form( array( 'context' => 'blog' ) ); ?>
    </div>

    <!-- Categories -->
    <div class="sidebar-block">
        <div class="sidebar-block-title"><?php esc_html_e( 'Categories', 'shopbar' ); ?></div>
        <ul class="sidebar-cat-list">
            <?php
            $categories = get_categories( array(
                'orderby' => 'name',
                'order'   => 'ASC',
                'number'  => 10,
            ) );
            foreach ( $categories as $category ) :
            ?>
            <li class="sidebar-cat-item">
                <a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>"><?php echo esc_html( $category->name ); ?></a>
                <span class="cat-count"><?php echo esc_html( $category->count ); ?></span>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <!-- Popular Posts -->
    <div class="sidebar-block">
        <div class="sidebar-block-title"><?php esc_html_e( 'Popular Posts', 'shopbar' ); ?></div>
        <?php
        $popular_posts = new WP_Query( array(
            'posts_per_page'      => 5,
            'ignore_sticky_posts' => 1,
            'meta_key'            => 'post_views_count',
            'orderby'             => 'meta_value_num',
            'order'               => 'DESC',
        ) );

        if ( ! $popular_posts->have_posts() ) {
            $popular_posts = new WP_Query( array(
                'posts_per_page'      => 5,
                'ignore_sticky_posts' => 1,
            ) );
        }

        if ( $popular_posts->have_posts() ) :
            while ( $popular_posts->have_posts() ) :
                $popular_posts->the_post();
        ?>
        <div class="popular-post">
            <a href="<?php the_permalink(); ?>" class="popular-thumb<?php echo ! has_post_thumbnail() ? ' no-image' : ''; ?>">
                <?php if ( has_post_thumbnail() ) : ?>
                    <?php the_post_thumbnail( 'thumbnail' ); ?>
                <?php endif; ?>
            </a>
            <div class="popular-info">
                <a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a>
                <span class="pop-date"><?php echo esc_html( get_the_date() ); ?></span>
            </div>
        </div>
        <?php
            endwhile;
            wp_reset_postdata();
        endif;
        ?>
    </div>

</aside>
