<?php
/**
 * File Path: includes/metaboxes/class-mbs-metabox-book-details.php
 *
 * Book Details Metabox
 *
 * F-020 Phase 3 (FREE tier, all tiers):
 *   mbs_language             ONIX language code (moved from Book Header, Sprint S112)
 *   mbs_featured             Featured / Promoted flag (moved from Book Header, Sprint S112)
 *   mbs_word_count           Word count integer (moved from Book Header, Sprint S112)
 *   mbs_show_word_count      Show word count publicly flag (moved from Book Header, Sprint S112)
 *   mbs_enable_reader_reviews Enable reader reviews per-book (moved from Book Header, Sprint S112)
 *   (edition_number + edition_type moved to mbs_format_rows per-format in Sprint S110)
 *   (mbs_teaser removed — canonical field is in MBS_Book_Header_Core_Render / MBS_Book_Header_Core_Save)
 *
 * @package My_Book_Showroom
 * @since   2.4.0
 */

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

/**
 * Class MBS_Metabox_Book_Details
 */
// phpcs:disable WordPress.Security.NonceVerification -- nonce verified in parent class verify_save() / check_admin_referer() before $_POST access; PHPCS cannot trace cross-method nonce verification
// 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_Metabox_Book_Details extends MBS_Metabox_Base { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	public function __construct() {
	}

	// -------------------------------------------------------------------------
	// Register
	// -------------------------------------------------------------------------


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

	public function render( WP_Post $post ): void {
		wp_nonce_field( 'mbs_book_details_save', 'mbs_book_details_nonce' );

		$language               = (string) get_post_meta( $post->ID, 'mbs_language',               true );
		if ( '' === $language ) {
			// SET-01: Fall back to the global default language when no per-book value is set (new books).
			$language = (string) get_option( 'mbs_setting_general_default_language', 'en' );
		}
		$is_featured            = (bool)   MBS_Book_Meta_DAO::get( $post->ID, 'mbs_featured', null );
		$word_count             = (int)    MBS_Book_Meta_DAO::get( $post->ID, 'mbs_word_count', 0 );
		$show_word_count        = (bool)   get_post_meta( $post->ID, 'mbs_show_word_count',        true );
		$reviews_enabled        = (bool)   get_post_meta( $post->ID, 'mbs_enable_reader_reviews',  true );
		$look_inside_text       = (string) get_post_meta( $post->ID, 'mbs_look_inside_text',             true );

		?>
		<table class="form-table mbs-book-details-table">

			<?php /* ── Language ────────────────────────────────────────── */ ?>
			<tr>
				<th scope="row">
					<label for="mbs_language">
						<?php esc_html_e( 'Language', 'my-book-showroom' ); ?>
					</label>
				</th>
				<td>
					<select id="mbs_language" name="mbs_language">
						<option value=""><?php esc_html_e( 'Select Language', 'my-book-showroom' ); ?></option>
						<option value="en" <?php selected( $language, 'en' ); ?>>en — English</option>
						<option value="es" <?php selected( $language, 'es' ); ?>>es — Spanish</option>
						<option value="fr" <?php selected( $language, 'fr' ); ?>>fr — French</option>
						<option value="de" <?php selected( $language, 'de' ); ?>>de — German</option>
						<option value="it" <?php selected( $language, 'it' ); ?>>it — Italian</option>
						<option value="pt" <?php selected( $language, 'pt' ); ?>>pt — Portuguese</option>
						<option value="ru" <?php selected( $language, 'ru' ); ?>>ru — Russian</option>
						<option value="zh" <?php selected( $language, 'zh' ); ?>>zh — Chinese</option>
						<option value="ja" <?php selected( $language, 'ja' ); ?>>ja — Japanese</option>
						<option value="ko" <?php selected( $language, 'ko' ); ?>>ko — Korean</option>
					</select>
				</td>
			</tr>

			<?php /* ── Featured / Promoted ───────────────────────────── */ ?>
			<tr>
				<th scope="row">
					<label for="mbs_featured">
						<?php esc_html_e( 'Featured / Promoted', 'my-book-showroom' ); ?>
					</label>
				</th>
				<td>
					<label>
						<input type="checkbox" id="mbs_featured" name="mbs_featured" value="1"
							<?php checked( $is_featured ); ?> />
						<?php esc_html_e( 'Mark as currently featured', 'my-book-showroom' ); ?>
					</label>
					<p class="description">
						<?php esc_html_e( 'Affects dashboard display and (PRO) layout sorting. Not a health dimension — no penalty for leaving unchecked.', 'my-book-showroom' ); ?>
					</p>
				</td>
			</tr>

			<?php /* ── Word Count ───────────────────────────────────────── */ ?>
			<tr>
				<th scope="row">
					<label for="mbs_word_count">
						<?php esc_html_e( 'Word Count', 'my-book-showroom' ); ?>
					</label>
				</th>
				<td>
					<input type="number" id="mbs_word_count" name="mbs_word_count" class="small-text"
						value="<?php echo esc_attr( $word_count ?: '' ); ?>"
						min="0" step="1" placeholder="e.g. 85000" />
					<label style="margin-left:12px;">
						<input type="checkbox" name="mbs_show_word_count" value="1" <?php checked( $show_word_count ); ?>>
						<?php esc_html_e( 'Show publicly', 'my-book-showroom' ); ?>
					</label>
					<p class="description"><?php esc_html_e( 'When shown, a reading time estimate (÷ 250 wpm) also appears on the front-end.', 'my-book-showroom' ); ?></p>
				</td>
			</tr>

			<?php /* ── Reader Reviews ─────────────────────────────────── */ ?>
			<tr>
				<th scope="row">
					<label for="mbs_enable_reader_reviews">
						<?php esc_html_e( 'Reader Reviews', 'my-book-showroom' ); ?>
					</label>
				</th>
				<td>
					<label>
						<input type="checkbox" id="mbs_enable_reader_reviews" name="mbs_enable_reader_reviews" value="1"
							<?php checked( $reviews_enabled ); ?> />
						<?php esc_html_e( 'Show reader reviews section on this book page', 'my-book-showroom' ); ?>
					</label>
					<p class="description">
						<?php esc_html_e( 'When enabled, approved reader reviews appear on the book page. Reviews use WordPress comments and require moderation.', 'my-book-showroom' ); ?>
					</p>
				</td>
			</tr>


			<?php /* ── Endorsements ──────────────────────────────── */ ?>
			<tr>
				<th colspan="2" class="mbs-section-heading">
					<?php esc_html_e( 'Endorsements', 'my-book-showroom' ); ?>
				</th>
			</tr>
			<tr>
				<td colspan="2">
					<?php
					$endorsements = MBS_Endorsement_DAO::get_all_for_post( $post->ID );
					?>
					<div class="mbs-repeater mbs-endorsements-repeater">
						<div class="mbs-repeater-rows">
							<?php if ( ! empty( $endorsements ) ) : ?>
								<?php foreach ( $endorsements as $endorsement ) : ?>
									<div class="mbs-repeater-row">
										<input type="hidden"
										       name="mbs_endorsement_id[]"
										       value="<?php echo esc_attr( $endorsement->id ); ?>">

										<textarea name="mbs_endorsement_quote[]"
										          class="large-text"
										          rows="3"
										          placeholder="Quote text..."><?php echo esc_textarea( $endorsement->quote_text ); ?></textarea>

										<input type="text"
										       name="mbs_endorsement_attributed_to[]"
										       class="widefat"
										       placeholder="Attributed to (name)"
										       value="<?php echo esc_attr( $endorsement->attributed_to ); ?>">

										<input type="text"
										       name="mbs_endorsement_attribution_title[]"
										       class="widefat"
										       placeholder="Title or publication"
										       value="<?php echo esc_attr( $endorsement->attribution_title ); ?>">

										<label>
											<input type="checkbox"
											       name="mbs_endorsement_visible[]"
											       value="1"
											       <?php checked( $endorsement->is_visible, 1 ); ?>>
											<?php esc_html_e( 'Visible on front-end', 'my-book-showroom' ); ?>
										</label>

										<button type="button"
										        class="button button-link-delete mbs-remove-row">
											<?php esc_html_e( 'Remove', 'my-book-showroom' ); ?>
										</button>
									</div>
								<?php endforeach; ?>
							<?php endif; ?>
						</div>

						<button type="button"
						        class="button button-primary mbs-add-endorsement-row">
							<?php esc_html_e( '+ Add Endorsement', 'my-book-showroom' ); ?>
						</button>
					</div>
				</td>
			</tr>

			<?php /* ── Look Inside / Sample Text ─────────────────────────── */ ?>
			<tr>
				<th colspan="2" class="mbs-section-heading">
					<?php esc_html_e( 'Look Inside / Sample Text', 'my-book-showroom' ); ?>
				</th>
			</tr>
			<tr>
				<td colspan="2" class="mbs-field-helper">
					<?php esc_html_e( 'The fastest method is to copy and paste Chapter 1 or your chosen excerpt directly into the editor below. Text pasted from Word, Google Docs, or any word processor preserves bold and italic formatting automatically.', 'my-book-showroom' ); ?>
					<?php if ( mbs_is_pro() ) : ?>
						<?php esc_html_e( 'Use the Upload buttons below to import from a .docx or .epub file.', 'my-book-showroom' ); ?>
					<?php endif; ?>
					<?php esc_html_e( 'Aim for 1,000–6,000 words.', 'my-book-showroom' ); ?>
				</td>
			</tr>
			<tr>
				<th><label for="mbs_look_inside_text"><?php esc_html_e( 'Look Inside Text', 'my-book-showroom' ); ?></label></th>
				<td>
					<?php
					wp_editor( $look_inside_text, 'mbs_look_inside_text', array(
						'media_buttons' => false,
						'textarea_rows' => 20,
						'teeny'         => true,
						'tinymce'       => array( 'toolbar1' => 'bold,italic' ),
					) );
					?>
					<p class="description">
						<span id="mbs-look-inside-wc">0</span> / 6,000 <?php esc_html_e( 'words', 'my-book-showroom' ); ?>
					</p>
				</td>
			</tr>
			<?php if ( mbs_is_pro() ) : ?>
			<tr>
				<td colspan="2" class="mbs-look-inside-upload-row">
					<div class="mbs-upload-btn-row">
						<button type="button" id="mbs-docx-upload-btn" class="button button-secondary">
							<?php esc_html_e( 'Upload Word Doc (.docx)', 'my-book-showroom' ); ?>
						</button>
						<input type="file" id="mbs-docx-file-input" accept=".docx" style="display:none">
						<span id="mbs-docx-status" class="mbs-upload-status"></span>
						<button type="button" id="mbs-epub-upload-btn" class="button button-secondary">
							<?php esc_html_e( 'Upload EPUB (.epub)', 'my-book-showroom' ); ?>
						</button>
						<input type="file" id="mbs-epub-file-input" accept=".epub" style="display:none">
						<span id="mbs-epub-status" class="mbs-upload-status"></span>
					</div>
					<p class="description">
						<?php esc_html_e( 'Imports are limited to the first 6,000 words.', 'my-book-showroom' ); ?>
					</p>
				</td>
			</tr>
			<?php endif; ?>
		</table>
		<?php
	}

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

	public function save( int $post_id, WP_Post $post ): void {
		if ( ! $this->verify_save( $post_id, 'mbs_book_details_nonce', 'mbs_book_details_save' ) ) {
			return;
		}

		// Language (moved from Book Header, Sprint S112).
		if ( isset( $_POST['mbs_language'] ) ) {
			update_post_meta( $post_id, 'mbs_language', sanitize_text_field( wp_unslash( $_POST['mbs_language'] ) ) );
		} else {
			update_post_meta( $post_id, 'mbs_language', '' );
		}

		// Featured / Promoted flag (moved from Book Header, Sprint S112).
		MBS_Book_Meta_DAO::upsert( $post_id, 'mbs_featured', absint( $_POST['mbs_featured'] ?? 0 ) );

		// Word Count + visibility (moved from Book Header, Sprint S112).
		$word_count = isset( $_POST['mbs_word_count'] ) ? absint( wp_unslash( $_POST['mbs_word_count'] ) ) : 0;
		MBS_Book_Meta_DAO::upsert( $post_id, 'mbs_word_count', $word_count );
		update_post_meta( $post_id, 'mbs_show_word_count', isset( $_POST['mbs_show_word_count'] ) ? 1 : 0 );

		// Reader Reviews toggle (moved from Book Header, Sprint S112).
		update_post_meta( $post_id, 'mbs_enable_reader_reviews', isset( $_POST['mbs_enable_reader_reviews'] ) ? 1 : 0 );

		// Endorsements — delegate to DAO (E-002 pattern).
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above via verify_save().
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitization performed by MBS_Endorsement_DAO::save_from_post() — see that method.
		MBS_Endorsement_DAO::save_from_post( $post_id, $_POST );

		// mbs_look_inside_text (Sprint 171)
		// wp_editor content is already clean HTML -- bypass the DOCX/EPUB sanitizer
		// and use wp_kses_post() directly. MBS_Look_Inside_Sanitizer::clean() is
		// reserved for EPUB/DOCX extraction paths (class-mbs-look-inside-ajax.php etc).
		if ( isset( $_POST['mbs_look_inside_text'] ) ) {
			$raw   = wp_unslash( $_POST['mbs_look_inside_text'] );
			$clean = wp_kses_post( $raw );
			if ( MBS_LOOK_INSIDE_WORD_LIMIT > 0 ) {
				$clean = MBS_Look_Inside_Sanitizer::apply_word_limit( $clean, MBS_LOOK_INSIDE_WORD_LIMIT );
			}
			if ( '' !== trim( wp_strip_all_tags( $clean ) ) ) {
				update_post_meta( $post_id, 'mbs_look_inside_text', $clean );
			} else {
				delete_post_meta( $post_id, 'mbs_look_inside_text' );
			}
		} else {
			delete_post_meta( $post_id, 'mbs_look_inside_text' );
		}
	}

	/**
	 * Render one editor section within the unified book editor shell.
	 *
	 * Passthrough — single-section handler (Sprint 169).
	 *
	 * @since  1.0.0
	 * @param  string  $section_key  Section key (ignored for single-section handlers).
	 * @param  WP_Post $post         Current post object.
	 * @return void
	 */
	public function render_section( string $section_key, WP_Post $post ): void {
		$this->render( $post );
	}

	/**
	 * Save one editor section within the unified book editor shell.
	 *
	 * Passthrough — single-section handler (Sprint 169).
	 *
	 * @since  1.0.0
	 * @param  string  $section_key  Section key (ignored for single-section handlers).
	 * @param  int     $post_id      Post ID.
	 * @param  WP_Post $post         Post object.
	 * @return void
	 */
	public function save_section( string $section_key, int $post_id, WP_Post $post ): void {
		$this->save( $post_id, $post );
	}

}
