<?php
/**
 * Default related posts template.
 *
 * To customise the output, copy this file to your theme:
 *   {your-theme}/igit-rpwt/template.php
 *
 * Variables available via $igit_rpwt_data:
 *   post_id    (int)      — the current post ID
 *   posts      (WP_Post[]) — array of related post objects
 *   settings   (array)    — full plugin settings array
 *   layout     (string)   — 'grid', 'list', or 'compact'
 *   show_thumb (bool)     — whether to show thumbnails
 *   show_title (bool)     — whether to show post titles
 *   thumb_size (string)   — registered image size name
 *
 * @package IGIT_RPWT
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template file; variables are scoped to this include.

$post_id    = $igit_rpwt_data['post_id'];
$posts      = $igit_rpwt_data['posts'];
$settings   = $igit_rpwt_data['settings'];
$layout     = $igit_rpwt_data['layout'];
$show_thumb = $igit_rpwt_data['show_thumb'];
$show_title = $igit_rpwt_data['show_title'];
$thumb_size = $igit_rpwt_data['thumb_size'];

$kses_heading  = array( 'h1' => array(), 'h2' => array(), 'h3' => array(), 'h4' => array(), 'h5' => array(), 'strong' => array(), 'em' => array() );
$wrapper_class = 'igit-rpwt igit-rpwt--' . esc_attr( $layout );
$wrapper_id    = '';
$orphan_css    = '';

// Build per-instance scoped CSS so every last-row item fills its equal share
// of the row width, regardless of how many orphans there are.
//
// Strategy: use the LCM of (cols, orphan_count) as the grid track count.
// Normal items span LCM/cols tracks; orphan items span LCM/orphan tracks.
// Example — 5 posts, 3 desktop cols:
//   orphan=2, LCM(3,2)=6 tracks, normal span=2, orphan span=3 → each 50%.
if ( 'grid' === $layout && ! empty( $posts ) ) {
	$n      = count( $posts );
	$cols_d = max( 2, min( 6, absint( $settings['grid_columns_desktop'] ) ) );
	$cols_t = max( 1, min( 3, absint( $settings['grid_columns_tablet'] ) ) );
	$cols_m = max( 1, min( 2, absint( $settings['grid_columns_mobile'] ) ) );

	$gcd = function( $a, $b ) use ( &$gcd ) {
		return $b === 0 ? $a : $gcd( $b, $a % $b );
	};

	$breakpoints = array(
		array( 'cols' => $cols_d, 'query' => '(min-width:769px)' ),
		array( 'cols' => $cols_t, 'query' => '(min-width:481px) and (max-width:768px)' ),
		array( 'cols' => $cols_m, 'query' => '(max-width:480px)' ),
	);

	$css_parts = array();
	foreach ( $breakpoints as $bp ) {
		$c      = $bp['cols'];
		$orphan = $c > 0 ? ( $n % $c ) : 0;
		if ( $orphan === 0 || $c === 1 ) {
			continue; // complete row or single-column — no adjustment needed.
		}
		if ( $orphan === 1 ) {
			// Single orphan: stretch to full row width.
			$css_parts[] = sprintf(
				'@media %s{#%s .igit-rpwt__item:last-child{grid-column:1/-1}}',
				$bp['query'], '%ID%'
			);
			continue;
		}
		// 2+ orphans: LCM-based equal-width spans.
		$lcm         = intval( ( $c * $orphan ) / $gcd( $c, $orphan ) );
		$normal_span = intval( $lcm / $c );
		$orphan_span = intval( $lcm / $orphan );
		$css_parts[] = sprintf(
			'@media %s{#%s .igit-rpwt__items{--igit-cols:%d}#%s .igit-rpwt__item{grid-column:span %d}#%s .igit-rpwt__item:nth-last-child(-n+%d){grid-column:span %d}}',
			$bp['query'],
			'%ID%', $lcm,
			'%ID%', $normal_span,
			'%ID%', $orphan, $orphan_span
		);
	}

	if ( ! empty( $css_parts ) ) {
		$wrapper_id = 'igit-rpwt-grid-' . absint( $post_id ) . '-' . wp_unique_id();
		$orphan_css = '<style>' . str_replace( '%ID%', esc_attr( $wrapper_id ), implode( '', $css_parts ) ) . '</style>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- entirely PHP-generated, no user input.
	}
}

$items_tag     = in_array( $layout, array( 'grid', 'masonry', 'carousel', 'chip' ), true ) ? 'div' : 'ul';
$item_tag      = in_array( $layout, array( 'grid', 'masonry', 'carousel', 'chip' ), true ) ? 'div' : 'li';
$query_time_ms = isset( $igit_rpwt_data['query_time_ms'] ) ? (float) $igit_rpwt_data['query_time_ms'] : 0.0;
?>
<?php echo $orphan_css; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- PHP-generated CSS, no user input. ?>
<div class="<?php echo esc_attr( $wrapper_class ); ?>"<?php if ( $wrapper_id ) : ?> id="<?php echo esc_attr( $wrapper_id ); ?>"<?php endif; ?>>

	<?php if ( ! empty( $settings['heading_text'] ) ) : ?>
		<div class="igit-rpwt__heading">
			<?php
			$ht = tag_escape( $settings['heading_level'] );
			echo '<' . $ht . '>' . wp_kses( $settings['heading_text'], $kses_heading ) . '</' . $ht . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $ht is sanitised with tag_escape().
			?>
			<?php if ( ! empty( $settings['show_query_time'] ) ) : ?>
				<span class="igit-rpwt__query-time"><?php echo esc_html( number_format( $query_time_ms, 1 ) ); ?>&thinsp;ms</span>
			<?php endif; ?>
		</div>
	<?php elseif ( ! empty( $settings['show_query_time'] ) ) : ?>
		<span class="igit-rpwt__query-time igit-rpwt__query-time--standalone"><?php echo esc_html( number_format( $query_time_ms, 1 ) ); ?>&thinsp;ms</span>
	<?php endif; ?>

	<?php if ( empty( $posts ) ) : ?>

		<p class="igit-rpwt__no-posts"><?php echo esc_html( $settings['no_posts_text'] ); ?></p>

	<?php else : ?>

		<?php if ( 'carousel' === $layout ) : ?>
		<div class="igit-rpwt__carousel-wrap">
			<button type="button" class="igit-rpwt__carousel-btn igit-rpwt__carousel-prev" aria-label="<?php esc_attr_e( 'Previous', 'igit-related-posts-with-thumb-images-after-posts' ); ?>">&#8249;</button>
			<<?php echo esc_attr( $items_tag ); ?> class="igit-rpwt__items">
		<?php else : ?>
		<<?php echo esc_attr( $items_tag ); ?> class="igit-rpwt__items">
		<?php endif; ?>

			<?php if ( 'chip' === $layout ) : ?>
				<?php foreach ( $posts as $related_post ) :
					$item_id  = absint( $related_post->ID );
					$item_url = ! empty( $related_post->igit_url ) ? $related_post->igit_url : get_permalink( $item_id );
					$link_target = ( ! empty( $settings['link_target'] ) && 'new' === $settings['link_target'] ) ? '_blank' : '_self';
				?>
				<div class="igit-rpwt__chip">
					<a href="<?php echo esc_url( $item_url ); ?>" target="<?php echo esc_attr( $link_target ); ?>"><?php echo esc_html( get_the_title( $item_id ) ); ?></a>
				</div>
				<?php endforeach; ?>
			<?php else : ?>

			<?php foreach ( $posts as $related_post ) :
				$item_id      = absint( $related_post->ID );
				$item_url     = ! empty( $related_post->igit_url ) ? $related_post->igit_url : get_permalink( $item_id );
				$item_title   = get_the_title( $item_id );
				$img_url      = $show_thumb ? IGIT_RPWT_Image_Helper::get_image_url( $item_id, $thumb_size ) : '';

				// Build link rel attribute.
				$rel_parts = array();
				if ( ! empty( $settings['link_nofollow'] ) ) {
					$rel_parts[] = 'nofollow';
				}
				if ( ! empty( $settings['link_target'] ) && 'new' === $settings['link_target'] ) {
					$rel_parts[] = 'noopener';
					$rel_parts[] = 'noreferrer';
				}
				$link_rel    = ! empty( $rel_parts ) ? implode( ' ', $rel_parts ) : '';
				$link_target = ( ! empty( $settings['link_target'] ) && 'new' === $settings['link_target'] ) ? '_blank' : '_self';

				// Build click-tracking data attributes (empty string when tracking is off or Pro is inactive).
				$tracking_attrs = '';
				if ( ! empty( $settings['enable_click_tracking'] ) && igit_rpwt_is_pro() ) {
					$tracking_attrs = ' data-igit-source="' . absint( $post_id ) . '" data-igit-target="' . absint( $item_id ) . '"';
				}

				// Capture item HTML so it can be filtered via igit_rpwt_render_item.
				ob_start();
			?>
			<<?php echo esc_attr( $item_tag ); ?> class="igit-rpwt__item">
				<a class="igit-rpwt__link"
					href="<?php echo esc_url( $item_url ); ?>"
					target="<?php echo esc_attr( $link_target ); ?>"
					<?php if ( $link_rel ) : ?>rel="<?php echo esc_attr( $link_rel ); ?>"<?php endif; ?>
					<?php echo $tracking_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				>
					<?php if ( $show_thumb && $img_url ) : ?>
						<span class="igit-rpwt__thumb-wrap">
							<img
								class="igit-rpwt__thumb"
								src="<?php echo esc_url( $img_url ); ?>"
								alt="<?php echo esc_attr( $item_title ); ?>"
								loading="lazy"
							/>
							<?php if ( ! empty( $settings['show_category_badge'] ) ) :
								$cats = get_the_category( $item_id );
								if ( ! empty( $cats ) ) : ?>
									<span class="igit-rpwt__cat-badge"><?php echo esc_html( $cats[0]->name ); ?></span>
								<?php endif;
							endif; ?>
						</span>
					<?php endif; ?>

					<span class="igit-rpwt__body">

						<?php if ( $show_title ) : ?>
							<span class="igit-rpwt__title"><?php echo esc_html( $item_title ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $settings['show_excerpt'] ) ) :
							$excerpt_length = absint( $settings['excerpt_length'] );
							$raw_excerpt    = get_the_excerpt( $item_id );
							$excerpt        = wp_trim_words( $raw_excerpt, $excerpt_length, '&hellip;' );
							if ( $excerpt ) : ?>
								<span class="igit-rpwt__excerpt"><?php echo esc_html( $excerpt ); ?></span>
							<?php endif;
						endif; ?>

						<?php
						// Meta badges row — only render wrapper if at least one badge is on.
						$show_any_badge = ! empty( $settings['show_date'] )
							|| ! empty( $settings['show_reading_time'] )
							|| ! empty( $settings['show_comment_count'] );

						if ( $show_any_badge ) : ?>
							<span class="igit-rpwt__meta">

								<?php if ( ! empty( $settings['show_date'] ) ) : ?>
									<span class="igit-rpwt__badge igit-rpwt__badge--date">
										<?php echo esc_html( get_the_date( get_option( 'date_format' ), $item_id ) ); ?>
									</span>
								<?php endif; ?>

								<?php if ( ! empty( $settings['show_reading_time'] ) ) :
									$word_count   = str_word_count( wp_strip_all_tags( get_post_field( 'post_content', $item_id ) ) );
									$reading_mins = max( 1, (int) ceil( $word_count / 200 ) );
								?>
									<span class="igit-rpwt__badge igit-rpwt__badge--read">
										<?php
										/* translators: %d = minutes */
										printf( esc_html( _n( '%d min read', '%d min read', $reading_mins, 'igit-related-posts-with-thumb-images-after-posts' ) ), absint( $reading_mins ) );
										?>
									</span>
								<?php endif; ?>

								<?php if ( ! empty( $settings['show_comment_count'] ) ) :
									$comment_count = (int) get_comments_number( $item_id );
								?>
									<span class="igit-rpwt__badge igit-rpwt__badge--comments">
										<?php
										/* translators: %d = comment count */
										printf( esc_html( _n( '%d comment', '%d comments', $comment_count, 'igit-related-posts-with-thumb-images-after-posts' ) ), absint( $comment_count ) );
										?>
									</span>
								<?php endif; ?>

							</span>
						<?php endif; ?>

					</span><!-- .igit-rpwt__body -->

				</a>
			</<?php echo esc_attr( $item_tag ); ?>>
				<?php
					$item_html = ob_get_clean();

					/**
					 * Filter the HTML for a single related post item.
					 *
					 * @param string  $item_html    The item's HTML.
					 * @param WP_Post $related_post The related post object.
					 * @param array   $settings     Plugin settings array.
					 */
					echo apply_filters( 'igit_rpwt_render_item', $item_html, $related_post, $settings ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				endforeach; ?>

			<?php endif; // end chip check ?>

		</<?php echo esc_attr( $items_tag ); ?>>

		<?php if ( 'carousel' === $layout ) : ?>
			<button type="button" class="igit-rpwt__carousel-btn igit-rpwt__carousel-next" aria-label="<?php esc_attr_e( 'Next', 'igit-related-posts-with-thumb-images-after-posts' ); ?>">&#8250;</button>
		</div><!-- .igit-rpwt__carousel-wrap -->
		<?php endif; ?>

		<?php
		// ── Schema.org ItemList JSON-LD ───────────────────────────────────────
		$schema_items = array();
		$position     = 1;
		foreach ( $posts as $related_post ) {
			$schema_items[] = array(
				'@type'    => 'ListItem',
				'position' => $position++,
				'url'      => get_permalink( $related_post->ID ),
				'name'     => html_entity_decode( get_the_title( $related_post->ID ), ENT_QUOTES, 'UTF-8' ),
			);
		}
		$schema = array(
			'@context'        => 'https://schema.org',
			'@type'           => 'ItemList',
			'name'            => html_entity_decode( wp_strip_all_tags( $settings['heading_text'] ), ENT_QUOTES, 'UTF-8' ),
			'itemListElement' => $schema_items,
		);
		?>
		<script type="application/ld+json"><?php echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); ?></script>

	<?php endif; ?>

</div>
