<?php
/**
 * Posts Block
 *
 * @package StrategyBlocks
 *
 * @param array  $attributes  The block's attributes.
 * @param string $content     The block's inner content.
 * @param object $block       The block object.
 */

use StrategyBlocks\FontAwesomeSVG;
use StrategyBlocks\Utility;

$id = ! empty( $attributes['anchor'] ) ? $attributes['anchor'] : '';
$layout = $attributes['layout'] ?? 'grid';
$slider_controls = $attributes['sliderControls'] ?? false;

$class_name = 'lg-block lg-block__posts posts';
$class_name .= 'slider' === $layout && $slider_controls ? ' swiper--nav' : '';
$class_name .= Utility\get_block_style_classes( $attributes );
$class_name .= Utility\get_native_wp_classes( $attributes );
$class_name .= Utility\get_visibility_classes( $attributes );
$animations = Utility\get_animation_data( $attributes );

// Convert image placement
$image_placement_map = [
	'top' => 'card--vertical',
	'left' => 'card--horizontal',
	'right' => 'card--horizontal reverse',
	'none' => null,
];

$card_class_name_attributes = [
	'base_class' => 'post card post__card bg-color-primary-shade-1 link-color-secondary text-color-secondary',
	'image_placement' => $image_placement_map[ $attributes['imagePlacement'] ] ?? null,
	'border' => $attributes['border'] ? 'card--bordered' : null,
	'border_radius' => 'none' !== $attributes['borderRadius'] ? 'rounded-' . $attributes['borderRadius'] : null,
	'border_color' => $attributes['borderColor'] ? 'border-color-' . $attributes['borderColor'] : null,
];
$card_class_name = implode( ' ', array_filter( $card_class_name_attributes ) );
$columns = 0 === $attributes['columns'] ? 1 : intval( $attributes['columns'] ?? 3 );

$class_name .= 'grid' === $layout
	? ' posts__grid posts__grid--' . $columns . ' posts__img--' . $attributes['imagePlacement']
	: ' posts__img--' . $attributes['imagePlacement'];
$class_name .= 'slider' === $layout ? ' posts__slider' : '';

$elements = $attributes['elements'] ?? [];

$args = [];

$paged = max( 1, (int) get_query_var( 'paged' ), (int) get_query_var( 'page' ) );

if ( $attributes['customQuery'] ) {
	$args = [
		'post_type'      => $attributes['postType'] ?? 'post',
		'post_status'    => 'publish',
		'posts_per_page' => intval( $attributes['numberOfPosts'] ?? 10 ),
		'paged'          => $paged,
	];

	$taxonomy = ! empty( $attributes['taxonomy'] ) ? sanitize_key( $attributes['taxonomy'] ) : '';
	$terms    = array_filter( array_map( 'intval', $attributes['terms'] ?? [] ) );

	if ( $taxonomy && ! empty( $terms ) ) {
		$args['tax_query'] = [
			[
				'taxonomy'         => $taxonomy,
				'field'            => 'term_id',
				'terms'            => $terms,
				'include_children' => true,
				'operator'         => 'IN',
			],
		];
	}
} else {
	rewind_posts();

	global $wp_query;
	$args = $wp_query->query_vars;
}

$slider_page_size = $columns;

$font_awesome = new FontAwesomeSVG( STRATEGY_BLOCKS_DIST_PATH . 'font-awesome/svgs' );
/**
 * Filters the SVG markup used for the Read More icon.
 *
 * @since TBD
 *
 * @param string $icon_id   The default icon ID used to generate the SVG.
 */
$icon_id = apply_filters( 'lg_posts_read_more_svg', 'fas fa-chevron-right' );
$svg = $font_awesome->get_svg( $icon_id, [ 'class' => 'btn-icon' ] );

$the_query = new WP_Query( $args );
$length = $the_query->post_count;

do_action( 'lg_block_posts_before' );
?>

<div <?php echo $id ? 'id="' . esc_attr( $id ) . '"' : ''; ?> class="<?php echo esc_attr( $class_name ); ?>" <?php echo $animations ? 'data-animation="' . esc_attr( $animations ) . '"' : ''; ?>>
	<?php
	if ( $the_query->have_posts() ) :
		if ( 'slider' === $layout ) :
			if ( ! empty( $id ) ) :
				?>
				<a id="skip-<?php echo esc_attr( $id ); ?>" class="skip-link" href="#after-<?php echo esc_attr( $id ); ?>"
					title="Skip Post Slider">Skip Past Post Slider</a>
			<?php endif; ?>
			<div class="posts__slider-wrapper swiper" data-swiper-perview="<?php echo esc_attr( $slider_page_size ); ?>">
				<div class="swiper-wrapper">
					<?php
					endif;
		while ( $the_query->have_posts() ) :
			$the_query->the_post();
			$link_post_titles = apply_filters( 'link_posts_headings', true, get_the_ID() );
			if ( 'slider' === $layout ) :
				?>
					<div class="swiper-slide">
							<?php endif; ?>
							<article class="<?php echo esc_attr( $card_class_name ); ?>">
								<?php if ( in_array( 'image', $elements, true ) && has_post_thumbnail() && ! is_null( $attributes['imagePlacement'] ) && 'none' !== $attributes['imagePlacement'] ) : ?>
									<div class="card__media post__image">
										<?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'medium_large', false, [ 'class' => 'card__media-img media__image' ] ); ?>
									</div>
								<?php endif; ?>
								<?php if ( ! empty( $elements ) ) : ?>
									<div class="card__content col">
										<?php foreach ( $elements as $element ) { ?>
											<?php if ( 'categories' === $element ) : ?>
												<?php
												$primary_term_id = function_exists( 'yoast_get_primary_term_id' ) ? yoast_get_primary_term_id() : false;
												$categories = $primary_term_id ? [ get_category( $primary_term_id ) ] : get_the_category();
												?>
												<p class="post__categories size-xs">
													<span class="sr-only">Posted In: </span>
													<?php
													foreach ( $categories as $category ) {
														printf(
															'<a href="%1$s" class="post__category">%2$s</a>',
															esc_url( get_category_link( $category->term_id ) ),
															esc_html( $category->name )
														);
													}
													?>
												</p>
											<?php endif; ?>

											<?php if ( 'title' === $element ) : ?>
												<<?php echo esc_attr( $attributes['titleHtmlTag'] ); ?> class="post__title h6">
													<?php if ( $link_post_titles ) : ?>
														<a href="<?php the_permalink(); ?>" class="post__title-link"><?php the_title(); ?></a>
													<?php else : ?>
														<?php the_title(); ?>
													<?php endif; ?>
												</<?php echo esc_attr( $attributes['titleHtmlTag'] ); ?>>
											<?php endif; ?>

											<?php if ( 'meta' === $element ) : ?>
												<div class="post__meta-items size-xs">
													<?php $meta_items = $attributes['metaItems'] ?? []; ?>
													<?php foreach ( $meta_items as $item ) { ?>
														<?php if ( 'author' === $item && ! empty( get_the_author() ) ) { ?>
															<span class="post__meta-item post__meta-author"><span class="sr-only">Posted By:
																</span><?php the_author(); ?></span>
														<?php } ?>
														<?php if ( 'date' === $item ) : ?>
															<span class="post__meta-item post__meta-date">
																<span class="sr-only"><?php esc_html_e( 'Posted On:', 'lead-gen' ); ?></span>
																<time datetime="<?php echo esc_attr( get_post_time( 'c', true ) ); ?>">
																	<?php echo esc_html( get_the_date( 'F jS, Y' ) ); ?>
																</time>
															</span>
														<?php endif; ?>

														<?php if ( 'date_time' === $item ) : ?>
															<span class="post__meta-item post__meta-datetime">
																<span class="sr-only"><?php esc_html_e( 'Posted On:', 'lead-gen' ); ?></span>
																<time datetime="<?php echo esc_attr( get_post_time( 'c', true ) ); ?>">
																	<?php echo esc_html( get_the_date( 'F jS, Y g:i a' ) ); ?>
																</time>
															</span>
														<?php endif; ?>
														<?php if ( 'reading_time' === $item ) { ?>
															<span
																class="post__meta-item post__meta-readingtime"><?php echo esc_html( Utility\get_reading_time( get_the_ID(), 250 ) ); ?></span>
														<?php } ?>
													<?php } ?>
												</div>
											<?php endif; ?>

											<?php if ( 'content' === $element ) : ?>
												<div class="post__excerpt">
													<?php $excerpt_length = $attributes['excerptLength'] ?? 25; ?>
													<?php Utility\sanitize_and_output_html_content( Utility\get_custom_excerpt( $excerpt_length ) ); ?>
												</div>
											<?php endif; ?>

											<?php if ( 'read_more' === $element ) : ?>
												<a href="<?php the_permalink(); ?>" class="post__btn btn btn-link btn-icon-after btn-left">
													<?php Utility\sanitize_and_output_svg( $svg ); ?>
													<span class="btn-text">Read More <span class="sr-only">About
															<?php the_title(); ?></span></span>
												</a>
											<?php endif; ?>
										<?php } ?>
									</div>
								<?php endif; ?>
							</article>
							<?php if ( 'slider' === $layout ) : ?>
						</div>
						<?php endif; ?>
					<?php endwhile; ?>
					<?php if ( 'slider' === $layout ) : ?>
				</div>
						<?php
						if ( $slider_controls ) {
							Utility\render_slider_controls( $font_awesome );
						}
						?>
			</div>
		<?php endif; ?>
		<?php
		if ( $attributes['pagination'] && 'slider' !== $layout ) {
			$total = (int) $the_query->max_num_pages;
			if ( $total > 1 ) {
				?>
				<nav class="posts__pagination">
					<?php
					Utility\pagination(
						[
							'total' => $total,
							'current' => $paged,
						]
					);
					?>
				</nav>
			<?php } ?>
		<?php } ?>
		<?php wp_reset_postdata(); ?>
	<?php else : ?>
		<p><?php echo esc_html( apply_filters( 'no_posts_message', 'Sorry, no posts matched your criteria.', $args ) ); ?>
		</p>
	<?php endif; ?>
	<?php if ( 'slider' === $layout && ! empty( $id ) ) { ?>
		<div id="after-<?php echo esc_attr( $id ); ?>" aria-hidden="true" class="sr-only"></div>
	<?php } ?>
</div>

<?php do_action( 'lg_block_posts_after' ); ?>
