<?php
/**
 * File Path: includes/blocks/class-mbs-block-coming-soon.php
 *
 * Coming Soon Block — Render
 *
 * PHP render_callback for the mbs/coming-soon Gutenberg block.
 * Shows books with mbs_coming_soon = '1' (set by PRO coming_soon lifecycle state).
 *
 * Tier gate: PRO only on front-end. FREE users see an HTML comment, no
 * visible output (GP-UI-1). The lifecycle state itself is PRO-only to set
 * via the book editor — this render class enforces the display gate.
 *
 * @package    My_Book_Showroom
 * @since      1.0.0
 */

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

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

	/**
	 * Render the Coming Soon block.
	 *
	 * Called by WordPress as the register_block_type render_callback.
	 * Uses MBS_Book_Query::build() with lifecycle_state=coming_soon, which
	 * bypasses the scheduled-release gate so future-dated books are included.
	 *
	 * @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_pro() ) {
			return '<!-- MBS: coming-soon requires PRO license -->';
		}

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

		$query_args = MBS_Book_Query::build( array(
			'per_page'        => $limit,
			'orderby'         => 'date',
			'order'           => 'ASC',   // Soonest first — most natural for upcoming books.
			'lifecycle_state' => 'coming_soon',
		) );

		// Exclude books whose publication date is today or in the past (matches badge Gate 3).
		// meta_query is already an AND array from MBS_Book_Query::build().
		$query_args['meta_query'][] = array(
			'relation' => 'OR',
			array( 'key' => 'mbs_pub_date', 'compare' => 'NOT EXISTS' ),
			array( 'key' => 'mbs_pub_date', 'value' => '', 'compare' => '=' ),
			array(
				'key'     => 'mbs_pub_date',
				'value'   => wp_date( 'Y-m-d' ),
				'compare' => '>',
				'type'    => 'DATE',
			),
		);

		$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;
	}
}
