<?php
/**
 * File Path: includes/metaboxes/class-mbs-metabox-publisher-imprint.php
 *
 * Publisher & Imprint Metabox
 *
 * F-020 Phase 4 — assigns mbs_publisher and mbs_imprint taxonomy
 * terms to a book. Both are FREE tier (Option B: two flat taxonomies).
 *
 * @package My_Book_Showroom
 * @since   2.4.0
 */

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

/**
 * Class MBS_Metabox_Publisher_Imprint
 */
// 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
class MBS_Metabox_Publisher_Imprint extends MBS_Metabox_Base { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	public function __construct() {
	}



	public function render( WP_Post $post ): void {
		wp_nonce_field( 'mbs_publisher_imprint_save', 'mbs_publisher_imprint_nonce' );

		// Current assignments.
		$is_pub             = mbs_is_pub();
		$pub_terms  = wp_get_object_terms( $post->ID, MBS_TAX_PUBLISHER, array( 'fields' => 'ids' ) );
		$imp_terms  = wp_get_object_terms( $post->ID, MBS_TAX_IMPRINT,   array( 'fields' => 'ids' ) );
		$pub_id     = ( ! is_wp_error( $pub_terms ) && ! empty( $pub_terms ) ) ? (int) $pub_terms[0] : 0;
		$imp_id     = ( ! is_wp_error( $imp_terms ) && ! empty( $imp_terms ) ) ? (int) $imp_terms[0] : 0;

		// All publisher terms.
		$publishers = get_terms( array(
			'taxonomy'   => MBS_TAX_PUBLISHER,
			'hide_empty' => false,
		) );
		// All imprint terms with their publisher_id term_meta.
		$imprints   = get_terms( array(
			'taxonomy'   => MBS_TAX_IMPRINT,
			'hide_empty' => false,
		) );
		?>
		<p>
			<label for="mbs_publisher_term" style="font-weight:600;">
				<?php esc_html_e( 'Publisher', 'my-book-showroom' ); ?>
			</label>
		</p>
		<select id="mbs_publisher_term" name="mbs_publisher_term" style="width:100%;">
			<option value="0"><?php esc_html_e( '-- None --', 'my-book-showroom' ); ?></option>
			<?php if ( ! is_wp_error( $publishers ) ) : ?>
				<?php foreach ( $publishers as $term ) : ?>
					<option value="<?php echo esc_attr( $term->term_id ); ?>" <?php selected( $pub_id, $term->term_id ); ?>>
						<?php echo esc_html( $term->name ); ?>
					</option>
				<?php endforeach; ?>
			<?php endif; ?>
		</select>

		<p style="margin-top:12px;">
			<label for="mbs_imprint_term" style="font-weight:600;">
				<?php esc_html_e( 'Imprint', 'my-book-showroom' ); ?>
			</label>
		</p>
		<select id="mbs_imprint_term" name="mbs_imprint_term" style="width:100%;">
			<option value="0"><?php esc_html_e( '-- None --', 'my-book-showroom' ); ?></option>
			<?php if ( ! is_wp_error( $imprints ) ) : ?>
				<?php foreach ( $imprints as $term ) : ?>
					<?php
					$term_pub_id = (int) get_term_meta( $term->term_id, 'mbs_publisher_id', true );
					?>
					<option value="<?php echo esc_attr( $term->term_id ); ?>"
						data-publisher-id="<?php echo esc_attr( $term_pub_id ); ?>"
						<?php selected( $imp_id, $term->term_id ); ?>>
						<?php echo esc_html( $term->name ); ?>
					</option>
				<?php endforeach; ?>
			<?php endif; ?>
		</select>
		<p class="description" style="margin-top:6px;">
			<?php esc_html_e( 'Imprints are linked to publishers via the Imprints term screen.', 'my-book-showroom' ); ?>
		</p>


		<!-- ── Copyright Disclaimer -- PUB tier only ──────────────────── -->
		<?php if ( $is_pub ) : ?>
		<?php
		$disclaimer_global = (string) get_option( 'mbs_pub_copyright_disclaimer', '' );
		$disclaimer_book   = (string) get_post_meta( $post->ID, 'mbs_copyright_disclaimer', true );
		?>
		<p style="margin-top:12px;">
			<label for="mbs_copyright_disclaimer" style="font-weight:600;">
				<?php esc_html_e( 'Copyright Disclaimer', 'my-book-showroom' ); ?>
			</label>
		</p>
		<textarea id="mbs_copyright_disclaimer" name="mbs_copyright_disclaimer"
			rows="4" style="width:100%;"><?php echo esc_textarea( $disclaimer_book ); ?></textarea>
		<p class="description">
			<?php
			if ( '' !== $disclaimer_global ) {
				printf(
					/* translators: %s: global disclaimer text */
					esc_html__( 'Leave blank to use the global disclaimer: %s', 'my-book-showroom' ),
					'<em>' . esc_html( wp_trim_words( $disclaimer_global, 12, "\u{2026}" ) ) . '</em>'
				);
			} else {
				esc_html_e( 'Leave blank to use the global disclaimer set in Publisher Tools &rarr; ONIX.', 'my-book-showroom' );
			}
			?>
		</p>
		<?php endif; ?>
		<?php
	}

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

		$is_pub_save = mbs_is_pub();

		// Publisher term.
		$pub_term_id = isset( $_POST['mbs_publisher_term'] ) ? absint( wp_unslash( $_POST['mbs_publisher_term'] ) ) : 0;
		if ( $pub_term_id > 0 ) {
			wp_set_object_terms( $post_id, $pub_term_id, MBS_TAX_PUBLISHER );
			// Sync canonical name to mbs_publisher postmeta so ONIX exporters,
			// front-end templates, and search shortcode all read the correct value.
			$pub_term = get_term( $pub_term_id, MBS_TAX_PUBLISHER );
			if ( $pub_term && ! is_wp_error( $pub_term ) ) {
				// C2-007: JS (admin-publisher.js) already syncs the term name into the
				// #mbs_publisher text field on dropdown change, so Book Header Core Save
				// (priority 10) is the authoritative writer when the user has any value
				// in that field. Only fall back to the term name here when the field is
				// empty (JS failed), preventing a manual override from being discarded.
				$bh_publisher = sanitize_text_field( wp_unslash( $_POST['mbs_publisher'] ?? '' ) );
				if ( '' === $bh_publisher ) {
					update_post_meta( $post_id, 'mbs_publisher', sanitize_text_field( $pub_term->name ) );
				}
			}
		} else {
			wp_set_object_terms( $post_id, array(), MBS_TAX_PUBLISHER );
		}

		// Imprint term.
		$imp_term_id = isset( $_POST['mbs_imprint_term'] ) ? absint( wp_unslash( $_POST['mbs_imprint_term'] ) ) : 0;
		if ( $imp_term_id > 0 ) {
			$imp_term = get_term( $imp_term_id, MBS_TAX_IMPRINT );
			if ( ! $imp_term || is_wp_error( $imp_term ) ) {
				$imp_term_id = 0;
			}
		}
		if ( $imp_term_id > 0 ) {
			wp_set_object_terms( $post_id, $imp_term_id, MBS_TAX_IMPRINT );
		} else {
			wp_set_object_terms( $post_id, array(), MBS_TAX_IMPRINT );
		}


		// Copyright Disclaimer (PUB tier only). Blank save deletes post meta → falls back to global.
		if ( $is_pub_save && isset( $_POST['mbs_copyright_disclaimer'] ) ) {
			$disclaimer = sanitize_textarea_field( wp_unslash( $_POST['mbs_copyright_disclaimer'] ) );
			if ( '' !== $disclaimer ) {
				update_post_meta( $post_id, 'mbs_copyright_disclaimer', $disclaimer );
			} else {
				delete_post_meta( $post_id, 'mbs_copyright_disclaimer' );
			}
		}
	}

	/**
	 * 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 );
	}

}
