<?php
/**
 * Trending News section.
 *
 * @package Rubik News
 */

$enable_trending_news = get_theme_mod( 'enable_trending_news', true );

if ( ! $enable_trending_news ) {
	return;
}

$section_title 	= get_theme_mod( 'trending_news_title', __( 'Trending Now', 'rubik-news' ) );
$category_id 	= absint( get_theme_mod( 'trending_news_category', 0 ) );
$posts_number 	= absint( get_theme_mod( 'trending_news_posts_number', 5 ) );
$show_number 	= get_theme_mod( 'trending_news_show_number', true );

$query_args = array(
	'post_type'           => 'post',
	'posts_per_page'      => $posts_number,
	'post_status'         => 'publish',
	'ignore_sticky_posts' => true,
	'no_found_rows'       => true,
);

if ( $category_id ) {
	$query_args['cat'] = $category_id;
}

$trending_news_query = new WP_Query( $query_args );

if ( $trending_news_query->have_posts() ) :
	$post_number = 1;
	?>
	<section class="trending-news-section">
		<div class="trending-news-header">
			<h2 class="trending-news-heading">
				<span class="trending-news-heading-icon" aria-hidden="true">
					<i class="fas fa-fire"></i>
				</span>

				<?php echo esc_html( $section_title ); ?>
			</h2>

			<span class="trending-news-heading-line"></span>
		</div><!-- .trending-news-header -->

		<div class="trending-news-grid">
			<?php
			while ( $trending_news_query->have_posts() ) :
				$trending_news_query->the_post();
				?>
				<article
					id="trending-post-<?php the_ID(); ?>"
					<?php post_class( 'trending-news-item' ); ?>
				>
					<div class="trending-news-thumbnail">
						<a
							href="<?php the_permalink(); ?>"
							aria-label="<?php echo esc_attr( get_the_title() ); ?>"
						>
							<?php
							if ( has_post_thumbnail() ) {
								the_post_thumbnail(
									'thumbnail',
									array(
										'loading' => 'lazy',
									)
								);
							} else {
								?>
								<span class="trending-news-placeholder"></span>
								<?php
							}
							?>
						</a>

						<?php if ( $show_number ) : ?>
							<span class="trending-news-number">
								<?php
								echo esc_html(
									str_pad(
										$post_number,
										2,
										'0',
										STR_PAD_LEFT
									)
								);
								?>
							</span>
						<?php endif; ?>
					</div><!-- .trending-news-thumbnail -->

					<div class="trending-news-content">
						<h3 class="trending-news-title">
							<a href="<?php the_permalink(); ?>">
								<?php the_title(); ?>
							</a>
						</h3>
					</div><!-- .trending-news-content -->
				</article>
				<?php
				$post_number++;
			endwhile;
			?>
		</div><!-- .trending-news-grid -->
	</section>
	<?php
	wp_reset_postdata();
endif;