<?php
/**
 * Frontpage Recent Articles Section.
 *
 * @package Hourly News
 */

// Recent Articles Section.
$recent_articles_section = get_theme_mod( 'hourly_news_recent_articles_section_enable', false );

if ( false === $recent_articles_section ) {
	return;
}

$content_ids                  = array();
$recent_articles_content_type = get_theme_mod( 'hourly_news_recent_articles_content_type', 'recent' );

if ( $recent_articles_content_type === 'post' ) {

	for ( $i = 1; $i <= 5; $i++ ) {
		$content_ids[] = get_theme_mod( 'hourly_news_recent_articles_post_' . $i );
	}

	$args = array(
		'post_type'           => 'post',
		'posts_per_page'      => absint( 5 ),
		'ignore_sticky_posts' => true,
	);
	if ( ! empty( array_filter( $content_ids ) ) ) {
		$args['post__in'] = array_filter( $content_ids );
		$args['orderby']  = 'post__in';
	} else {
		$args['orderby'] = 'date';
	}
} else {
	$args = array(
		'post_type'           => 'post',
		'posts_per_page'      => absint( 5 ),
		'ignore_sticky_posts' => true,
	);
}

$query = new WP_Query( $args );
if ( $query->have_posts() ) {
	$section_title  = get_theme_mod( 'hourly_news_recent_articles_title', __( 'Recent Articles', 'hourly-news' ) );
	$button_label   = get_theme_mod( 'hourly_news_recent_articles_button_label', __( 'View All', 'hourly-news' ) );
	$button_url     = get_theme_mod( 'hourly_news_recent_articles_button_url', __( '#', 'hourly-news' ) );
	?>
	<section id="hourly_news_recent_articles_section" class="recent-articles section-divider recent-layout-2">
		<div class="site-container-width">
			<?php if ( ! empty( $section_title || $button_label ) ) : ?>
				<div class="header-title">
					<h3 class="section-title"><?php echo esc_html( $section_title ); ?></h3>
					<?php if ( ! empty( $button_label ) ) : ?>
						<a href="<?php echo esc_url( $button_url ); ?>" class="view-all"><?php echo esc_html( $button_label ); ?></a>
					<?php endif; ?>
				</div>
			<?php endif; ?>
			<div class="container-wrap">
				<?php
				$i = 1;
				while ( $query->have_posts() ) :
					$query->the_post();
					?>
					<div class="single-card-container <?php echo esc_attr( $i === 1 ? 'tile-card' : 'list-card' ); ?>">
						<div class="single-card-image">
							<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
						</div>
						<div class="single-card-detail">
							<?php hourly_news_categories_list(); ?>
							<h3 class="card-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
							<div class="card-meta">
								<?php
									hourly_news_posted_by();
									hourly_news_posted_on();
								?>
							</div>
						</div>
					</div>
					<?php
					$i++;
				endwhile;
				wp_reset_postdata();
				?>
			</div>
		</div>
	</section>

	<?php
}
