<?php
/**
 * File Path: includes/taxonomies/class-mbs-taxonomy-genre.php
 *
 * Genre Taxonomy
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Taxonomy_Genre {
	use MBS_Taxonomy_Layout_Field_Trait;

	/**
	 * Return the taxonomy constant for the layout field trait.
	 *
	 * @return string
	 */
	protected static function layout_taxonomy_key(): string {
		return MBS_TAX_GENRE;
	}

	/**
	 * Genre has no settings-notice row and therefore no View button.
	 *
	 * @return bool
	 */
	protected static function show_view_button_row(): bool {
		return false;
	}

	public static function register(): void {
		$labels = array(
			'name'          => __( 'Genres', 'my-book-showroom' ),
			'singular_name' => __( 'Genre', 'my-book-showroom' ),
			'menu_name'     => __( 'Genres', 'my-book-showroom' ),
		);

		register_taxonomy(
			MBS_TAX_GENRE,
			MBS_POST_TYPE,
			array(
				'labels'            => $labels,
				'hierarchical'      => true,
				'public'            => true,
				'show_ui'           => true,
				'show_in_rest'      => true,
				'show_admin_column' => true,
				// MENU-01: Prevent menu.php from auto-attaching to edit.php?post_type=mbs_book.
				// MBS_Admin::add_menu() registers the Genres submenu manually.
				'show_in_menu'          => false,
				'show_in_quick_edit'    => false,
				// RF-013: Count all non-trashed statuses, not just published (latent bug fix).
				'update_count_callback' => array( __CLASS__, 'update_term_count_all' ),
			)
		);

		if ( is_admin() ) {
			add_action( MBS_TAX_GENRE . '_edit_form_fields', array( __CLASS__, 'render_layout_field' ), 20, 2 );
			add_action( 'edited_' . MBS_TAX_GENRE,            array( __CLASS__, 'save_layout_field' ) );
			add_action( 'admin_enqueue_scripts',               array( __CLASS__, 'enqueue_layout_scripts' ) );
		}
	}

	/**
	 * Term count callback: count all non-trashed post statuses.
	 *
	 * WordPress core's _update_post_term_count() only counts published posts.
	 * This callback counts every non-trashed status so term counts stay accurate
	 * during active editing (drafts, private, pending, future).
	 *
	 * Registered via 'update_count_callback' on all four MBS taxonomies
	 * (RF-013: fixes the latent bug where genre/series/universe showed 0 for
	 * non-published books).
	 *
	 * @param int[]       $terms    Array of term taxonomy IDs to update.
	 * @param WP_Taxonomy $taxonomy Taxonomy object (unused; required by WP).
	 * @return void
	 */
	public static function update_term_count_all( array $terms, WP_Taxonomy $taxonomy ): void {
		foreach ( $terms as $ttid ) {
			MBS_Taxonomy_Count_DAO::update_term_book_count( (int) $ttid );
		}
	}

}
