<?php
/**
 * File Path: includes/blocks/class-mbs-block-reading-order.php
 *
 * Reading Order Block -- Render
 *
 * PHP render_callback for the mbs/reading-order Gutenberg block.
 * Registered by MBS_Blocks_Registry::register_reading_order_block().
 *
 * Renders a numbered reading-order list for a named series, pulling
 * data from MBS_Series_Reading_Order_DAO. No cover grid -- title and
 * author only, linked to each book's permalink. PRO-gated.
 *
 * Attributes:
 *   slug (string) -- mbs_series term slug. Default empty (none selected).
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Blocks
 * @since      1.0.0
 */

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

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

	public static function render( array $attributes ): string {
		if ( ! mbs_is_registered() ) {
			return '';
		}

		if ( ! mbs_is_pro() ) {
			return '<!-- MBS: reading-order requires PRO license -->';
		}

		$slug = sanitize_title( $attributes['slug'] ?? '' );
		if ( ! $slug ) {
			return '';
		}

		$term = get_term_by( 'slug', $slug, 'mbs_series' );
		if ( ! $term || is_wp_error( $term ) ) {
			return '';
		}

		$book_ids = MBS_Series_Reading_Order_DAO::get_ordered_book_ids( $term->term_id );
		if ( empty( $book_ids ) ) {
			return '';
		}

		$html  = '<div class="mbs-wrapper mbs-block-reading-order">';
		$html .= '<ol class="mbs-reading-order-list">';
		foreach ( $book_ids as $position => $book_id ) {
			$title     = get_the_title( $book_id );
			$permalink = get_permalink( $book_id );
			$author    = implode( ', ', wp_list_pluck(
				wp_get_post_terms( $book_id, 'mbs_author', array( 'fields' => 'all' ) ),
				'name'
			) );
			$html .= '<li class="mbs-reading-order-item">';
			$html .= '<a href="' . esc_url( $permalink ) . '">' . esc_html( $title ) . '</a>';
			if ( $author ) {
				$html .= ' <span class="mbs-reading-order-author">by ' . esc_html( $author ) . '</span>';
			}
			$html .= '</li>';
		}
		$html .= '</ol>';
		$html .= '</div>';

		return $html;
	}
}
