<?php
/**
 * Blog Posts Section — server-side render.
 *
 * Outputs a single wrapper div with data-attributes for the React
 * frontend to hydrate. No PHP-rendered HTML — React handles all output.
 *
 * A WP_Query always runs and the resolved posts are injected under
 * $attributes['_runtime']['posts'] before JSON-encoding.
 *
 * Output is sanitised via wp_json_encode() + esc_attr().
 *
 * @package SectionCollection
 */

// Bail if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$bpsc_query_args = array(
	'post_type'           => sanitize_key( $attributes['query']['postType'] ?? 'post' ),
	'posts_per_page'      => min( 24, max( 1, intval( $attributes['query']['postCount'] ?? 6 ) ) ),
	'orderby'             => in_array(
		$attributes['query']['orderBy'] ?? 'date',
		array( 'date', 'title', 'modified', 'rand' ),
		true
	) ? $attributes['query']['orderBy'] : 'date',
	'order'               => strtoupper( $attributes['query']['order'] ?? 'DESC' ) === 'ASC' ? 'ASC' : 'DESC',
	'post_status'         => 'publish',
	'ignore_sticky_posts' => true,
);

$bpsc_query           = new WP_Query( $bpsc_query_args );
$bpsc_open_in_new_tab = ! empty( $attributes['query']['openInNewTab'] );
$bpsc_resolved_posts  = array();

while ( $bpsc_query->have_posts() ) {
	$bpsc_query->the_post();
	$bpsc_post_id   = get_the_ID();
	$bpsc_thumb_id  = get_post_thumbnail_id( $bpsc_post_id );
	$bpsc_thumb_url = $bpsc_thumb_id ? wp_get_attachment_image_url( $bpsc_thumb_id, 'large' ) : '';
	$bpsc_thumb_alt = $bpsc_thumb_id ? get_post_meta( $bpsc_thumb_id, '_wp_attachment_image_alt', true ) : '';

	// Primary category — first term from the first taxonomy registered for the post type.
	$bpsc_category_name = '';
	$bpsc_taxonomies    = get_object_taxonomies( get_post_type(), 'names' );
	foreach ( $bpsc_taxonomies as $bpsc_tax ) {
		$bpsc_terms = get_the_terms( $bpsc_post_id, $bpsc_tax );
		if ( ! empty( $bpsc_terms ) && ! is_wp_error( $bpsc_terms ) ) {
			$bpsc_category_name = $bpsc_terms[0]->name;
			break;
		}
	}

	$bpsc_author_id   = get_post_field( 'post_author', $bpsc_post_id );
	$bpsc_excerpt_raw = get_the_excerpt();

	$bpsc_resolved_posts[] = array(
		'id'           => (string) $bpsc_post_id,
		'image'        => array(
			'url' => $bpsc_thumb_url ? esc_url( $bpsc_thumb_url ) : '',
			'alt' => $bpsc_thumb_alt ? esc_attr( $bpsc_thumb_alt ) : '',
			'id'  => (int) $bpsc_thumb_id,
		),
		// Top-level imageAlt for PostCard compatibility.
		'imageAlt'     => $bpsc_thumb_alt ? esc_attr( $bpsc_thumb_alt ) : '',
		'category'     => esc_html( $bpsc_category_name ),
		'title'        => esc_html( get_the_title() ),
		'excerpt'      => wp_strip_all_tags( $bpsc_excerpt_raw ),
		'author'       => esc_html( get_the_author_meta( 'display_name', $bpsc_author_id ) ),
		'authorAvatar' => array(
			'url' => esc_url( get_avatar_url( $bpsc_author_id, array( 'size' => 96 ) ) ),
			'alt' => esc_html( get_the_author_meta( 'display_name', $bpsc_author_id ) ),
			'id'  => 0,
		),
		'date'         => esc_html( get_the_date( 'F j, Y', $bpsc_post_id ) ),
		'readTime'     => '',
		'url'          => esc_url( get_permalink( $bpsc_post_id ) ),
		'urlNewTab'    => $bpsc_open_in_new_tab,
	);
}
wp_reset_postdata();

// Inject resolved posts under _runtime so view.js can extract them.
$bpsc_attributes            = $attributes;
$bpsc_attributes['_runtime'] = array( 'posts' => $bpsc_resolved_posts );

$id = wp_unique_id( 'bpscBlogPostsSection-' );
?>
<div
	<?php echo wp_kses_data( get_block_wrapper_attributes() ); ?>
	id="<?php echo esc_attr( $id ); ?>"
	data-attributes="<?php echo esc_attr( wp_json_encode( $bpsc_attributes ) ); ?>"
></div>
