<?php
/**
 * File Path: includes/blocks/class-mbs-block-new-releases.php
 *
 * New Releases Block — Render
 *
 * PHP render_callback for the mbs/new-releases Gutenberg block.
 * Shows books whose mbs_publication_date falls within the last N days.
 * FREE tier — gates on mbs_is_registered().
 *
 * @package    My_Book_Showroom
 * @since      1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class MBS_Block_New_Releases { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Valid publication window options (days).
	 *
	 * @var int[]
	 */
	private const VALID_DAYS = array( 30, 60, 90, 180 );

	/**
	 * Render the New Releases block.
	 *
	 * Called by WordPress as the register_block_type render_callback.
	 * Uses MBS_Book_Query::build() with publication_window so the
	 * scheduled-release gate and all standard filters compose cleanly.
	 *
	 * @param array $attributes Block attributes from the editor.
	 * @return string Rendered HTML or empty string (GP-UI-1: no placeholder on front-end).
	 */
	public static function render( array $attributes ): string {
		if ( ! mbs_is_registered() ) {
			return '<!-- MBS: new-releases requires a registered license -->';
		}

		$limit = max( 1, absint( $attributes['limit'] ?? 6 ) );
		$days  = absint( $attributes['days'] ?? 30 );

		// Clamp to valid options; default 30 for any unrecognized value.
		if ( ! in_array( $days, self::VALID_DAYS, true ) ) {
			$days = 30;
		}

		$query_args = MBS_Book_Query::build( array(
			'per_page'           => $limit,
			'orderby'            => 'date',
			'order'              => 'DESC',
			'publication_window' => $days,
		) );

		$query = new WP_Query( $query_args );

		if ( ! $query->have_posts() ) {
			wp_reset_postdata();
			return '';
		}

		$layout_slug = mbs_get_setting( 'formatting', 'default_layout', 'grid' );
		$layout_obj  = MBS_Layout_Registry::get_layout( $layout_slug );
		$output      = $layout_obj->render( $query );
		wp_reset_postdata();

		return $output;
	}
}
