<?php
/**
 * File Path: includes/shortcodes/class-mbs-shortcode-timeline.php
 *
 * [mbs_timeline] Shortcode -- DISPLAY-1
 *
 * Renders a vertical publication timeline for a book: one entry per format
 * edition (mbs_format_rows row) plus ARC date entries where present.
 * FREE tier -- no license gate beyond mbs_is_registered().
 *
 * Attributes:
 *   book_id (int, optional) -- book post ID; defaults to current post.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

/**
 * Class MBS_Shortcode_Timeline
 *
 * Shortcode handler for [mbs_timeline]. Resolves the target book, gathers
 * format rows and ARC dates, then delegates rendering to the timeline partial.
 *
 * @since 1.0.0
 */
class MBS_Shortcode_Timeline { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Render the [mbs_timeline] shortcode.
	 *
	 * @param array $atts Raw shortcode attributes.
	 * @return string Rendered HTML or HTML comment on failure.
	 */
	public static function render( array $atts ): string {
		if ( ! mbs_is_registered() ) {
			return '';
		}

		$atts = shortcode_atts(
			array(
				'book_id' => 0,
			),
			$atts,
			'mbs_timeline'
		);

		$book_id = (int) $atts['book_id'];
		if ( ! $book_id ) {
			$book_id = get_the_ID();
		}

		if ( ! $book_id || get_post_type( $book_id ) !== MBS_POST_TYPE ) {
			return '<!-- MBS: mbs_timeline requires a valid mbs_book post -->';
		}

		$format_rows = MBS_Format_Row_DAO::get_by_post( $book_id );

		if ( empty( $format_rows ) ) {
			return '<!-- MBS: no format editions found for timeline -->';
		}

		$campaign = MBS_Arc_Recipient_DAO::get_campaign( $book_id );
		$arc_data = array(
			'open_date'  => $campaign ? (string) ( $campaign->distribution_date  ?? '' ) : '',
			'close_date' => $campaign ? (string) ( $campaign->close_date         ?? '' ) : '',
			'deadline'   => $campaign ? (string) ( $campaign->target_review_date ?? '' ) : '',
		);

		ob_start();
		mbs_get_template_part(
			'partials/timeline',
			array(
				'format_rows' => $format_rows,
				'arc_data'    => $arc_data,
				'book_id'     => $book_id,
			)
		);
		return ob_get_clean();
	}
}
