<?php
/**
 * File Path: includes/blocks/class-mbs-block-book-club.php
 *
 * Block: mbs/book-club (PRO)
 *
 * Renders the Book Club Resources section for a specific book post.
 *
 * Attribute:
 *   postId (int, default 0) — the book to render. When 0, falls back to
 *   get_the_ID() so the block works inside single-book templates and Query
 *   Loop contexts without requiring an explicit selection.
 *
 * PRO gate: returns an HTML comment on FREE installs — no visible output.
 * GP-UI-1: returns empty string when the author has visibility toggled off
 *          or when all content fields are empty.
 *
 * Registered in class-mbs-blocks-registry.php via register_book_club_block().
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Blocks
 * @since      1.0.0
 */

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

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

	/**
	 * Render callback for the mbs/book-club block.
	 *
	 * @param array $attributes Block attributes from the editor.
	 * @return string Rendered HTML or empty string / HTML comment.
	 */
	public static function render( array $attributes ): string {
		if ( ! mbs_is_pro() ) {
			return '<!-- MBS: book-club requires PRO license -->';
		}

		// Resolve post ID: explicit attribute takes precedence; fall back to loop context.
		$post_id = isset( $attributes['postId'] ) && $attributes['postId'] > 0
			? absint( $attributes['postId'] )
			: (int) get_the_ID();

		if ( ! $post_id ) {
			return '';
		}

		// Visibility gate (DAT-028) — read from DAO, not stale postmeta.
		$_bc_header = MBS_Book_Club_DAO::get_header( $post_id );
		if ( ! $_bc_header['enabled'] ) {
			return '';
		}

		// Content guard (GP-UI-1) — skip render entirely when nothing is saved.
		$guide     = $_bc_header['guide'];
		$questions = MBS_Book_Club_DAO::get_questions( $post_id );
		$files     = MBS_Book_Club_DAO::get_files( $post_id );

		$has_guide     = '' !== trim( (string) $guide );
		$has_questions = ! empty( $questions );
		$has_files     = ! empty( $files );

		if ( ! $has_guide && ! $has_questions && ! $has_files ) {
			return '';
		}

		// Output-buffer the shared template partial. $post_id is in scope for the include.
		ob_start();
		include MBS_TEMPLATES_DIR . 'partials/section-book-club-resources.php';
		return (string) ob_get_clean();
	}
}
