<?php
/**
 * File Path: includes/admin/class-mbs-admin-native-bulk-edit-render.php
 *
 * MBS Admin — Native Bulk & Quick Edit Render Class
 *
 * Flat taxonomy configuration is sourced from:
 *   MBS_Admin_Native_Bulk_Edit::flat_taxonomies()
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

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

	// =========================================================================
	// Hidden data column
	// =========================================================================

	/**
	 * Render term IDs as a JSON data attribute in the hidden column cell.
	 * child-admin-inline-edit.js reads these when a quick edit panel opens.
	 *
	 * @param string $column  Column name.
	 * @param int    $post_id Current post ID.
	 */
	public static function render_data_column( string $column, int $post_id ): void {
		if ( 'mbs_book_data' !== $column ) {
			return;
		}

		$series_terms = wp_get_object_terms( $post_id, MBS_TAX_SERIES, array( 'fields' => 'ids' ) );
		$series_id    = ( ! is_wp_error( $series_terms ) && ! empty( $series_terms ) )
			? (int) reset( $series_terms )
			: 0;

		// Derive reading-order position: 1-based index in the series reading order list.
		$reading_order_pos = 0;
		if ( $series_id > 0 && class_exists( 'MBS_Series_Reading_Order_DAO' ) ) {
			$ordered_ids = MBS_Series_Reading_Order_DAO::get_ordered_book_ids( $series_id );
			$ro_idx      = array_search( $post_id, $ordered_ids, true );
			if ( false !== $ro_idx ) {
				$reading_order_pos = $ro_idx + 1;
			}
		}

		$term_data = array(
			'series'           => $series_id,
			'series_position'  => (string) get_post_meta( $post_id, 'mbs_series_position', true ),
			'reading_order_pos'=> $reading_order_pos,
			'authors'          => self::get_term_ids( $post_id, MBS_TAX_AUTHOR ),
			'tags'             => self::get_term_ids( $post_id, MBS_TAX_TAG ),
			'collections'      => self::get_term_ids( $post_id, MBS_TAX_COLLECTION ),
			'universes'        => self::get_term_ids( $post_id, MBS_TAX_UNIVERSE ),
			'themes'           => self::get_term_ids( $post_id, MBS_TAX_THEME ),
			'warnings'         => self::get_term_ids( $post_id, MBS_TAX_CONTENT_WARNING ),
		);

		echo '<span class="hidden mbs-inline-edit-data" '
			. 'data-mbs-terms="' . esc_attr( wp_json_encode( $term_data ) ) . '">'
			. '</span>';
	}

	/**
	 * Return an array of integer term IDs for a given post + taxonomy.
	 *
	 * @param  int    $post_id  Post ID.
	 * @param  string $taxonomy Taxonomy slug.
	 * @return int[]
	 */
	private static function get_term_ids( int $post_id, string $taxonomy ): array {
		$terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
		return is_wp_error( $terms ) ? array() : array_map( 'intval', $terms );
	}

	/**
	 * Hide the mbs_book_data column header and cells via an inline <style>.
	 * The column must exist in the columns array so WordPress calls the
	 * bulk/quick edit box actions for it, but it must never be visible.
	 */
	public static function hide_data_column_css(): void {
		$screen = get_current_screen();
		if ( ! $screen || 'edit-' . MBS_POST_TYPE !== $screen->id ) {
			return;
		}
		echo '<style>.column-mbs_book_data { display: none !important; }</style>' . "\n";
	}

	// =========================================================================
	// Bulk edit fields
	// =========================================================================

	/**
	 * Render MBS taxonomy fields inside the native WordPress bulk edit panel.
	 * Fires once per column; we key on 'mbs_book_data' and render exactly once.
	 *
	 * @param string $column    Column name.
	 * @param string $post_type Post type slug.
	 */
	public static function render_bulk_edit_fields( string $column, string $post_type ): void {
		if ( 'mbs_book_data' !== $column || MBS_POST_TYPE !== $post_type ) {
			return;
		}

		$series_terms = get_terms( array(
			'taxonomy'   => MBS_TAX_SERIES,
			'hide_empty' => false,
			'orderby'    => 'name',
		) );

		wp_nonce_field( 'mbs_inline_edit', 'mbs_inline_edit_nonce' );
		// Sentinel: signals save_fields() that our panel was submitted.
		echo '<input type="hidden" name="mbs_inline_edit_active" value="1">';
		?>
		<fieldset class="inline-edit-col-right mbs-inline-edit-fieldset">
			<div class="inline-edit-col">

				<h4 class="mbs-inline-edit-heading">
					<?php esc_html_e( 'Book Showroom', 'my-book-showroom' ); ?>
				</h4>

				<!-- ── Series: single-select (1:1) ───────────────────────── -->
				<label class="mbs-inline-edit-label">
					<span class="title"><?php esc_html_e( 'Series', 'my-book-showroom' ); ?></span>
					<select name="mbs_inline_series" id="mbs-bulk-series">
						<option value=""><?php esc_html_e( '— No change —', 'my-book-showroom' ); ?></option>
						<option value="__remove__"><?php esc_html_e( '(Remove from series)', 'my-book-showroom' ); ?></option>
						<?php if ( ! is_wp_error( $series_terms ) ) : ?>
							<?php foreach ( $series_terms as $series ) : ?>
								<option value="<?php echo esc_attr( $series->term_id ); ?>">
									<?php echo esc_html( $series->name ); ?>
								</option>
							<?php endforeach; ?>
						<?php endif; ?>
					</select>
				</label>

				<!-- ── Flat taxonomies: checkbox lists (append to existing) ── -->
				<?php foreach ( MBS_Admin_Native_Bulk_Edit::flat_taxonomies() as $taxonomy => $config ) : ?>
					<?php
					$terms = get_terms( array(
						'taxonomy'   => $taxonomy,
						'hide_empty' => false,
						'orderby'    => 'name',
					) );
					if ( is_wp_error( $terms ) || empty( $terms ) ) {
						continue;
					}
					?>
					<div class="mbs-inline-edit-checklist-wrap">
						<span class="mbs-inline-edit-tax-label">
							<?php echo esc_html( $config['label'] ); ?>
						</span>
						<p class="mbs-inline-edit-append-note">
							<?php esc_html_e( 'Adds to existing — does not remove', 'my-book-showroom' ); ?>
						</p>
						<ul class="mbs-inline-edit-checklist"
						    id="mbs-bulk-<?php echo esc_attr( $config['key'] ); ?>">
							<?php foreach ( $terms as $term ) : ?>
								<li>
									<label>
										<input type="checkbox"
										       name="mbs_inline_tax[<?php echo esc_attr( $taxonomy ); ?>][]"
										       value="<?php echo esc_attr( $term->term_id ); ?>">
										<?php echo esc_html( $term->name ); ?>
									</label>
								</li>
							<?php endforeach; ?>
						</ul>
					</div>
				<?php endforeach; ?>

			</div>
		</fieldset>
		<?php
	}

	// =========================================================================
	// Quick edit fields
	// =========================================================================

	/**
	 * Render MBS taxonomy fields inside the native WordPress quick edit panel.
	 * Fires once per column; we key on 'mbs_book_data' and render exactly once.
	 *
	 * @param string $column    Column name.
	 * @param string $post_type Post type slug.
	 */
	public static function render_quick_edit_fields( string $column, string $post_type ): void {
		if ( 'mbs_book_data' !== $column || MBS_POST_TYPE !== $post_type ) {
			return;
		}

		$series_terms = get_terms( array(
			'taxonomy'   => MBS_TAX_SERIES,
			'hide_empty' => false,
			'orderby'    => 'name',
		) );

		wp_nonce_field( 'mbs_inline_edit', 'mbs_inline_edit_nonce' );
		echo '<input type="hidden" name="mbs_inline_edit_active" value="1">';
		?>
		<fieldset class="inline-edit-col-right mbs-inline-edit-fieldset">
			<div class="inline-edit-col">

				<h4 class="mbs-inline-edit-heading">
					<?php esc_html_e( 'Book Showroom', 'my-book-showroom' ); ?>
				</h4>

				<!-- ── Series: single-select (1:1) ───────────────────────── -->
				<label class="mbs-inline-edit-label">
					<span class="title"><?php esc_html_e( 'Series', 'my-book-showroom' ); ?></span>
					<select name="mbs_inline_series" id="mbs-qe-series">
						<option value=""><?php esc_html_e( '(No series)', 'my-book-showroom' ); ?></option>
						<?php if ( ! is_wp_error( $series_terms ) ) : ?>
							<?php foreach ( $series_terms as $series ) : ?>
								<option value="<?php echo esc_attr( $series->term_id ); ?>">
									<?php echo esc_html( $series->name ); ?>
								</option>
							<?php endforeach; ?>
						<?php endif; ?>
					</select>
				</label>

				<!-- ── Series Position ──────────────────────────────────────── -->
				<label class="mbs-inline-edit-label">
					<span class="title"><?php esc_html_e( 'Position', 'my-book-showroom' ); ?></span>
					<input type="text"
					       name="mbs_inline_series_position"
					       id="mbs-qe-series-position"
					       class="small-text"
					       value=""
					       placeholder="<?php esc_attr_e( 'e.g. 1, 0.5', 'my-book-showroom' ); ?>"
					       autocomplete="off">
				</label>

				<!-- ── Reading Order (read-only, derived from series term_meta) ── -->
				<div class="mbs-inline-edit-reading-order-wrap">
					<span class="mbs-inline-edit-tax-label">
						<?php esc_html_e( 'Reading Order', 'my-book-showroom' ); ?>
					</span>
					<span id="mbs-qe-reading-order-pos" class="mbs-inline-edit-reading-order-pos">&mdash;</span>
					<span class="mbs-inline-edit-reading-order-note">
						<?php esc_html_e( 'Position in series narrative order. Edit via Catalog → Series.', 'my-book-showroom' ); ?>
					</span>
				</div>

				<!-- ── Flat taxonomies: checkbox lists (replaces on save) ── -->
				<?php foreach ( MBS_Admin_Native_Bulk_Edit::flat_taxonomies() as $taxonomy => $config ) : ?>
					<?php
					$terms = get_terms( array(
						'taxonomy'   => $taxonomy,
						'hide_empty' => false,
						'orderby'    => 'name',
					) );
					if ( is_wp_error( $terms ) || empty( $terms ) ) {
						continue;
					}
					?>
					<div class="mbs-inline-edit-checklist-wrap">
						<span class="mbs-inline-edit-tax-label">
							<?php echo esc_html( $config['label'] ); ?>
						</span>
						<ul class="mbs-inline-edit-checklist"
						    id="mbs-qe-<?php echo esc_attr( $config['key'] ); ?>">
							<?php foreach ( $terms as $term ) : ?>
								<li>
									<label>
										<input type="checkbox"
										       name="mbs_inline_tax[<?php echo esc_attr( $taxonomy ); ?>][]"
										       value="<?php echo esc_attr( $term->term_id ); ?>">
										<?php echo esc_html( $term->name ); ?>
									</label>
								</li>
							<?php endforeach; ?>
						</ul>
					</div>
				<?php endforeach; ?>

			</div>
		</fieldset>
		<?php
	}
}
