<?php
/**
 * File Path: includes/metaboxes/book-header/class-mbs-book-header-extended-meta.php
 *
 * Book Header Child Section — Extended Metadata
 *
 * Story S13-11 (Phase 1 / FREE):
 *   New fields: reading age range, grade level, edition name/number,
 *   awards & accolades.
 *
 *   Also: admin notes are demoted from PRO-only to FREE in this sprint;
 *   the gate removal is handled in class-mbs-book-header-notes.php.
 *
 * Meta keys (all FREE, stored as post_meta):
 *   Note: Illustrator (A12) and Translator (B06) removed Session 106;
 *   both roles are handled by the Contributors metabox (mbs_book_contributors).
 *   mbs_awards             — awards and accolades, stored in mbs_book_awards table via
 *                               MBS_Book_Awards_DAO (R2-001). JSON-encoded post_meta path removed. ALL tier.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Metaboxes/BookHeader
 * @since      1.0.0
 */

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

/**
 * Class MBS_Book_Header_Extended_Meta
 */
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- input sanitized at point of use (sanitize_text_field, absint, wp_kses_post, etc.); false positives from PHPCS not tracing sanitization helpers called before this method
class MBS_Book_Header_Extended_Meta { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	public function __construct() {
		add_action( 'mbs_book_header_render_extended_meta', array( $this, 'render' ) );
		add_action( 'mbs_book_header_save_extended_meta',   array( $this, 'save' ), 10, 2 );
	}

	// -------------------------------------------------------------------------
	// Render
	// -------------------------------------------------------------------------

	/**
	 * Render extended-metadata fields inside the Book Header metabox.
	 *
	 * @param WP_Post $post Current post object.
	 */
	public function render( $post ): void {
		$awards_rows = MBS_Book_Awards_DAO::get( $post->ID );
		wp_nonce_field( 'mbs_save_awards_' . $post->ID, 'mbs_awards_nonce' );
		?>


		
		<?php /* ── Awards & Accolades — repeater (Sprint CE-1) ─────────────── */ ?>
		<tr>
			<th scope="row">
				<?php esc_html_e( 'Awards & Accolades', 'my-book-showroom' ); ?>
			</th>
			<td>
				<div class="mbs-awards-repeater">

					<div class="mbs-awards-rows" id="mbs-awards-rows">
						<?php foreach ( $awards_rows as $i => $award_row ) : ?>
						<div class="mbs-award-row" style="display:flex;align-items:center;gap:8px;margin-bottom:6px;flex-wrap:wrap;">
							<input type="text"
							       name="mbs_awards_rows[<?php echo esc_attr( $i ); ?>][name]"
							       class="regular-text mbs-award-name"
							       value="<?php echo esc_attr( $award_row['name'] ?? '' ); ?>"
							       placeholder="<?php esc_attr_e( 'Award name', 'my-book-showroom' ); ?>">
							<input type="number"
							       name="mbs_awards_rows[<?php echo esc_attr( $i ); ?>][year]"
							       class="small-text mbs-award-year"
							       value="<?php echo esc_attr( $award_row['year'] ?? '' ); ?>"
							       min="1900" max="2100" step="1"
							       placeholder="<?php esc_attr_e( 'Year', 'my-book-showroom' ); ?>">
							<select name="mbs_awards_rows[<?php echo esc_attr( $i ); ?>][status]" class="mbs-award-status">
								<option value=""><?php esc_html_e( '— Status —', 'my-book-showroom' ); ?></option>
								<?php
								foreach ( self::award_statuses() as $val => $label ) :
									printf(
										'<option value="%s"%s>%s</option>',
										esc_attr( $val ),
										selected( $award_row['status'] ?? '', $val, false ),
										esc_html( $label )
									);
								endforeach;
								?>
							</select>
							<button type="button" class="button-link mbs-remove-award-row" aria-label="<?php esc_attr_e( 'Remove award', 'my-book-showroom' ); ?>">
								&#x2715;
							</button>
						</div>
						<?php endforeach; ?>
					</div>

					<?php /* Hidden template row — display:none must stay inline. */ ?>
					<div id="awards-row-template" class="mbs-award-row-template" style="display:none;">
						<div class="mbs-award-row" style="display:flex;align-items:center;gap:8px;margin-bottom:6px;flex-wrap:wrap;">
							<input type="text"
							       name="mbs_awards_rows[0][name]"
							       class="regular-text mbs-award-name"
							       value=""
							       disabled
							       placeholder="<?php esc_attr_e( 'Award name', 'my-book-showroom' ); ?>">
							<input type="number"
							       name="mbs_awards_rows[0][year]"
							       class="small-text mbs-award-year"
							       value=""
							       min="1900" max="2100" step="1"
							       disabled
							       placeholder="<?php esc_attr_e( 'Year', 'my-book-showroom' ); ?>">
							<select name="mbs_awards_rows[0][status]" class="mbs-award-status" disabled>
								<option value=""><?php esc_html_e( '— Status —', 'my-book-showroom' ); ?></option>
								<?php
								foreach ( self::award_statuses() as $val => $label ) :
									printf( '<option value="%s">%s</option>', esc_attr( $val ), esc_html( $label ) );
								endforeach;
								?>
							</select>
							<button type="button" class="button-link mbs-remove-award-row" aria-label="<?php esc_attr_e( 'Remove award', 'my-book-showroom' ); ?>">
								&#x2715;
							</button>
						</div>
					</div>

					<button type="button" class="button mbs-add-award-row" style="margin-top:8px;">
						<?php esc_html_e( '+ Add Award', 'my-book-showroom' ); ?>
					</button>

				</div>
			</td>
		</tr>

		<?php
	}

	// -------------------------------------------------------------------------
	// Save
	// -------------------------------------------------------------------------

	/**
	 * Save extended-metadata fields for the current post.
	 *
	 * All fields are FREE. Input is sanitized and stored via MBS_Book_Awards_DAO.
	 *
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post    Post object.
	 */
	public function save( int $post_id, $post ): void {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		// V8-B-012: Awards save requires explicit nonce + capability — cannot rely solely on hook chain.
		if ( ! isset( $_POST['mbs_awards_nonce'] ) || ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['mbs_awards_nonce'] ) ),
			'mbs_save_awards_' . $post_id
		) ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Awards — JSON-encoded array of {name, year, status} objects (Sprint CE-1).
		$raw_rows    = isset( $_POST['mbs_awards_rows'] ) && is_array( $_POST['mbs_awards_rows'] )
		               ? wp_unslash( $_POST['mbs_awards_rows'] )
		               : array();
		$raw_rows = array_slice( $raw_rows, 0, 50 ); // V8-B-014: Cap at 50 awards per book.
		$valid_statuses = array_keys( self::award_statuses() );
		$awards_data = array();
		foreach ( $raw_rows as $row ) {
			$name = sanitize_text_field( $row['name'] ?? '' );
			if ( '' === $name ) {
				continue; // Discard empty-name rows including the hidden template row.
			}
			$year_raw = isset( $row['year'] ) && '' !== (string) $row['year']
			            ? absint( $row['year'] )
			            : '';
			if ( '' !== $year_raw ) {
				$year_raw = max( 1900, min( 2100, $year_raw ) );
			}
			$status = sanitize_key( $row['status'] ?? '' );
			$status = in_array( $status, $valid_statuses, true ) ? $status : '';
			$awards_data[] = array(
				'name'   => $name,
				'year'   => $year_raw,
				'status' => $status,
			);
		}
		MBS_Book_Awards_DAO::save( $post_id, $awards_data );
	}
	// -------------------------------------------------------------------------
	// Helpers
	// -------------------------------------------------------------------------

	/**
	 * Canonical list of award status values.
	 * Used in both render() and save() to keep statuses in sync.
	 *
	 * @return array<string,string> Key = stored value, Value = display label.
	 */
	private static function award_statuses(): array {
		return array(
			'winner'             => __( 'Winner',            'my-book-showroom' ),
			'finalist'           => __( 'Finalist',          'my-book-showroom' ),
			'nominee'            => __( 'Nominee',           'my-book-showroom' ),
			'honorable_mention'  => __( 'Honorable Mention', 'my-book-showroom' ),
			'longlist'           => __( 'Longlist',          'my-book-showroom' ),
		);
	}

}
