<?php
/**
 * File Path: includes/blocks/class-mbs-block-catalog.php
 *
 * MBS Catalog Block — PHP Render Callback
 *
 * Render callback for the `mbs/catalog` Gutenberg block (Story 13-16).
 * Registered by MBS_Blocks_Registry::register_catalog_block().
 *
 * Delegates to MBS_Shortcode_Books::render() so the block and the
 * [mbs_books] shortcode share identical output logic (AC 1).
 *
 * PRO layout enforcement (AC 6):
 *   FREE layouts (grid, list, masonry, hero) are always available.
 *   If a PRO-only layout slug is stored in the block attribute and
 *   mbs_is_pro() is false, falls back to 'grid' silently.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Blocks
 * @since      1.0.0
 */

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

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

	/** Layout slugs available on the FREE tier. */
	const FREE_LAYOUTS = array( 'grid', 'list', 'masonry', 'hero' );

	/**
	 * Render the MBS Catalog block.
	 *
	 * Called by WordPress as the register_block_type render_callback.
	 * Maps block attributes to MBS_Shortcode_Books::render() parameters.
	 *
	 * @param array $attributes Block attributes from the editor.
	 * @return string Rendered HTML.
	 */
	public static function render( array $attributes ): string {
		// PRO layout guard (AC 6): fall back to 'grid' on FREE tier.
		$layout = sanitize_key( $attributes['layout'] ?? 'grid' );
		if ( ! mbs_is_pro() && ! in_array( $layout, self::FREE_LAYOUTS, true ) ) {
			$layout = 'grid';
		}

		// BLK-CATALOG-2: Suppress pagination in the editor preview.
		// ServerSideRender pagination links are real <a> tags; clicking them
		// navigates the editor page to the paginated URL, producing a REST 404.
		$in_editor = defined( 'REST_REQUEST' ) && REST_REQUEST;

		$shortcode_atts = array(
			'layout'          => $layout,
			'columns'         => max( 1, min( 6, (int) ( $attributes['columns'] ?? 3 ) ) ),
			'per_page'        => max( 1, min( 48, (int) ( $attributes['limit']   ?? 6 ) ) ),
			'orderby'         => sanitize_key( $attributes['orderby'] ?? 'date' ),
			'show_pagination' => ! $in_editor,
			// Taxonomy filters — passed through only when non-empty.
			'author'          => sanitize_text_field( $attributes['author'] ?? '' ),
			'series'          => sanitize_text_field( $attributes['series'] ?? '' ),
			'genre'           => sanitize_text_field( $attributes['genre']  ?? '' ),
			'tag'             => sanitize_text_field( $attributes['tag']    ?? '' ),
		);

		return MBS_Shortcode_Books::render( $shortcode_atts );
	}
}
