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

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

// 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_Taxonomy_Author {

	public static function register(): void {
		$labels = array(
			'name'              => __( 'Authors', 'my-book-showroom' ),
			'singular_name'     => __( 'Author', 'my-book-showroom' ),
			'menu_name'         => __( 'Authors', 'my-book-showroom' ),
			'all_items'         => __( 'All Authors', 'my-book-showroom' ),
			'add_new_item'      => __( 'Add New Author', 'my-book-showroom' ),
			'new_item_name'     => __( 'New Author Name', 'my-book-showroom' ),
			// Screen title on the native WordPress term-edit page (term.php).
			'edit_item'         => __( 'Edit Author Slug', 'my-book-showroom' ),
			'update_item'       => __( 'Update Author', 'my-book-showroom' ),
			'search_items'      => __( 'Search Authors', 'my-book-showroom' ),
			'not_found'         => __( 'No authors found.', 'my-book-showroom' ),
			'no_terms'          => __( 'No authors', 'my-book-showroom' ),
		);

		register_taxonomy(
			MBS_TAX_AUTHOR,
			MBS_POST_TYPE,
			array(
				'labels'            => $labels,
				'hierarchical'      => false,
				'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 Authors submenu manually.
				'show_in_menu'      => false,
				'show_in_quick_edit' => false,
			)
		);

		if ( is_admin() ) {
			self::register_term_meta_hooks();
		}
	}

	public static function register_term_meta_hooks(): void {
		add_action( MBS_TAX_AUTHOR . '_add_form_fields',  array( __CLASS__, 'add_form_fields' ) );
		add_action( MBS_TAX_AUTHOR . '_edit_form_fields', array( __CLASS__, 'render_settings_notice' ),  5, 2 );
		add_action( MBS_TAX_AUTHOR . '_edit_form_fields', array( __CLASS__, 'edit_form_fields' ), 10, 2 );
		add_action( 'created_' . MBS_TAX_AUTHOR,          array( __CLASS__, 'save_term_meta' ) );
		add_action( 'edited_'  . MBS_TAX_AUTHOR,          array( __CLASS__, 'save_term_meta' ) );
		add_action( 'admin_enqueue_scripts',               array( __CLASS__, 'enqueue_scripts' ) );
	}


	/**
	 * Render a navigation notice on the native WordPress Edit Term screen.
	 *
	 * Points editors to Settings → Authors for the full rich editing UI.
	 * The slug is the only field that must be edited here.
	 *
	 * @param WP_Term $term Current term object (unused — notice is generic).
	 */
	public static function render_settings_notice( WP_Term $term ): void {
		$settings_url = admin_url( 'admin.php?page=my-book-showroom-settings&tab=authors' );
		$term_link    = get_term_link( $term );
		if ( ! is_wp_error( $term_link ) ) {
			?>
		<tr class="mbs-settings-view-row">
			<th scope="row"></th>
			<td style="padding-top:4px;">
				<a href="<?php echo esc_url( $term_link ); ?>"
				   class="button button-secondary button-small"
				   target="_blank"
				   rel="noopener noreferrer">
					<?php esc_html_e( 'View Author →', 'my-book-showroom' ); ?>
				</a>
			</td>
		</tr>
			<?php
		}
		?>
		<tr class="mbs-settings-notice-row">
			<td colspan="2" style="padding-left:0;padding-right:0;">
				<div class="notice notice-info inline" style="margin:0;">
					<p>
						<?php
						echo wp_kses_post( sprintf(
						/* translators: %s: link to My Book Showroom → Settings → Authors */
						__( 'To edit the bio, photo, social links, and other details, go to %s. This screen manages the slug only.', 'my-book-showroom' ),
						'<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'My Book Showroom → Settings → Authors', 'my-book-showroom' ) . '</a>'
						) );
						?>
					</p>
				</div>
			</td>
		</tr>
		<?php
	}
	public static function add_form_fields(): void {
		?>
		<div class="form-field">
			<label for="mbs_is_corporate">
				<input type="checkbox" id="mbs_is_corporate" name="mbs_is_corporate" value="1">
				<?php esc_html_e( 'Organization (not a person)', 'my-book-showroom' ); ?>
			</label>
		</div>
		<?php /* F-NAMES-1: structured name fields — persons only */ ?>
		<h3 style="margin-bottom:6px"><?php esc_html_e( 'Name structure (for sorting &amp; ONIX)', 'my-book-showroom' ); ?></h3>
		<p class="description" style="margin-bottom:12px"><?php esc_html_e( 'Optional. Leave blank if not a named person.', 'my-book-showroom' ); ?></p>
		<div class="form-field">
			<label for="mbs_name_titles_before"><?php esc_html_e( 'Title / Honorific', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_titles_before" name="mbs_name_titles_before"
				placeholder="<?php esc_attr_e( 'Dr., Sir, Prof.', 'my-book-showroom' ); ?>">
		</div>
		<div class="form-field">
			<label for="mbs_name_before_key"><?php esc_html_e( 'First / middle name(s)', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_before_key" name="mbs_name_before_key"
				placeholder="<?php esc_attr_e( 'Mary Jo, John A.', 'my-book-showroom' ); ?>">
		</div>
		<div class="form-field">
			<label for="mbs_name_prefix_to_key"><?php esc_html_e( 'Surname prefix', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_prefix_to_key" name="mbs_name_prefix_to_key"
				placeholder="<?php esc_attr_e( 'van der, de, von', 'my-book-showroom' ); ?>">
		</div>
		<div class="form-field">
			<label for="mbs_name_key"><?php esc_html_e( 'Surname / Last Name (key name)', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_key" name="mbs_name_key"
				placeholder="<?php esc_attr_e( 'Smith, van der Berg', 'my-book-showroom' ); ?>">
		</div>
		<div class="form-field">
			<label for="mbs_name_after_key"><?php esc_html_e( 'Suffix', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_after_key" name="mbs_name_after_key"
				placeholder="<?php esc_attr_e( 'Jr., III', 'my-book-showroom' ); ?>">
		</div>
		<div class="form-field">
			<label for="mbs_name_letters"><?php esc_html_e( 'Letters after name', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_letters" name="mbs_name_letters"
				placeholder="<?php esc_attr_e( 'PhD, OBE, CBE', 'my-book-showroom' ); ?>">
		</div>
		<div class="form-field">
			<label for="mbs_name_inverted"><?php esc_html_e( 'Inverted name (sort / ONIX PersonNameInverted)', 'my-book-showroom' ); ?></label>
			<input type="text" id="mbs_name_inverted" name="mbs_name_inverted"
				placeholder="<?php esc_attr_e( 'Auto-computed from fields above when left blank', 'my-book-showroom' ); ?>">
			<p class="description"><?php esc_html_e( 'Leave blank to auto-compute from surname + first name fields.', 'my-book-showroom' ); ?></p>
		</div>
		<?php
	}

	public static function edit_form_fields( WP_Term $term ): void {
		?>
		<?php if ( mbs_is_pro() ) :
			$current_layout = (string) get_term_meta( $term->term_id, 'mbs_term_layout', true );
			$layouts        = MBS_Layout_Registry::get_layout_options();
		?>
		<tr class="form-field mbs-term-layout-row">
			<th scope="row">
				<label for="mbs_term_layout"><?php esc_html_e( 'Book Grid Layout', 'my-book-showroom' ); ?></label>
			</th>
			<td>
				<select name="mbs_term_layout" id="mbs_term_layout">
					<option value=""><?php esc_html_e( '— Use global default —', 'my-book-showroom' ); ?></option>
					<?php foreach ( $layouts as $slug => $meta ) : ?>
						<option value="<?php echo esc_attr( $slug ); ?>"
							<?php selected( $current_layout, $slug ); ?>
							<?php echo ( ! empty( $meta['pro'] ) ) ? 'data-pro="1"' : ''; ?>>
							<?php echo esc_html( $meta['label'] . ( ! empty( $meta['pro'] ) ? ' (PRO)' : '' ) ); ?>
						</option>
					<?php endforeach; ?>
				</select>
				<div id="mbs-term-layout-desc" class="mbs-layout-description"></div>
				<p class="description">
					<?php esc_html_e( 'Override the global default layout for this author\'s book grid. Leave blank to use the global default from Settings → Formatting.', 'my-book-showroom' ); ?>
				</p>
			</td>
		</tr>
		<?php endif; ?>
		<?php /* F-NAMES-1: structured name fields */ ?>
		<tr><th colspan="2"><h3 style="margin:8px 0 4px"><?php esc_html_e( 'Name structure (for sorting &amp; ONIX)', 'my-book-showroom' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Optional. Leave blank if not a named person.', 'my-book-showroom' ); ?></p></th></tr>
		<?php
		$name_fields = array(
			'mbs_name_titles_before'  => array( 'label' => __( 'Title / Honorific', 'my-book-showroom' ),                              'placeholder' => 'Dr., Sir, Prof.' ),
			'mbs_name_before_key'     => array( 'label' => __( 'First / middle name(s)', 'my-book-showroom' ),                         'placeholder' => 'Mary Jo, John A.' ),
			'mbs_name_prefix_to_key'  => array( 'label' => __( 'Surname prefix', 'my-book-showroom' ),                                 'placeholder' => 'van der, de, von' ),
			'mbs_name_key'            => array( 'label' => __( 'Surname / Last Name (key name)', 'my-book-showroom' ),                             'placeholder' => 'Smith, van der Berg' ),
			'mbs_name_after_key'      => array( 'label' => __( 'Suffix', 'my-book-showroom' ),                                         'placeholder' => 'Jr., III' ),
			'mbs_name_letters'        => array( 'label' => __( 'Letters after name', 'my-book-showroom' ),                             'placeholder' => 'PhD, OBE, CBE' ),
			'mbs_name_inverted'       => array( 'label' => __( 'Inverted name (sort / ONIX PersonNameInverted)', 'my-book-showroom' ),  'placeholder' => __( 'Auto-computed from fields above when left blank', 'my-book-showroom' ) ),
		);
		foreach ( $name_fields as $meta_key => $field ) :
			$val = (string) get_term_meta( $term->term_id, $meta_key, true );
		?>
		<tr class="form-field">
			<th scope="row"><label for="<?php echo esc_attr( $meta_key ); ?>"><?php echo esc_html( $field['label'] ); ?></label></th>
			<td><input type="text" id="<?php echo esc_attr( $meta_key ); ?>" name="<?php echo esc_attr( $meta_key ); ?>"
				value="<?php echo esc_attr( $val ); ?>"
				placeholder="<?php echo esc_attr( $field['placeholder'] ); ?>"></td>
		</tr>
		<?php endforeach; ?>
		<?php
	}

	public static function enqueue_scripts( string $hook ): void {
		if ( 'edit-tags.php' !== $hook && 'term.php' !== $hook ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( sanitize_key( wp_unslash( $_GET['taxonomy'] ?? '' ) ) !== MBS_TAX_AUTHOR ) {
			return;
		}
		wp_enqueue_script(
			'mbs-admin-taxonomy-author',
			plugins_url( 'assets/js/mbs-admin-taxonomy-author.js', MBS_DIR . 'bookshowroom.php' ),
			array(),
			MBS_VERSION,
			true
		);

		// Hide the native WordPress Description field: MBS manages author bios
		// exclusively via Settings → Authors. The Description field is unused
		// and would confuse authors who already filled it in via the WP screen.
		wp_add_inline_style( 'forms', '.term-description-wrap { display: none !important; }' );

		// SHC-6: layout description panel (PRO only).
		if ( mbs_is_pro() ) {
			wp_enqueue_script( 'mbs-admin-layout-desc' );
			wp_set_script_translations( 'mbs-admin-layout-desc', 'my-book-showroom', MBS_DIR . 'languages' );
			wp_add_inline_script(
				'mbs-admin-layout-desc',
				"jQuery( function() { if ( typeof MBS_LayoutDesc !== 'undefined' ) { MBS_LayoutDesc.init( '#mbs_term_layout', '#mbs-term-layout-desc' ); } } );"
			);
		}
	}

	public static function save_term_meta( int $term_id ): void {
		// F-NAMES-1: structured name fields.
		$simple_name_keys = array(
			'mbs_name_titles_before',
			'mbs_name_before_key',
			'mbs_name_prefix_to_key',
			'mbs_name_key',
			'mbs_name_after_key',
			'mbs_name_letters',
		);
		foreach ( $simple_name_keys as $key ) {
			$val = isset( $_POST[ $key ] )
				? sanitize_text_field( wp_unslash( $_POST[ $key ] ) )
				: '';
			update_term_meta( $term_id, $key, $val );
		}

		// mbs_name_inverted: use manual entry or auto-compute from structured parts.
		$name_inverted = isset( $_POST['mbs_name_inverted'] )
			? sanitize_text_field( wp_unslash( $_POST['mbs_name_inverted'] ) )
			: '';
		if ( '' === $name_inverted ) {
			$name_key           = isset( $_POST['mbs_name_key'] ) ? sanitize_text_field( wp_unslash( $_POST['mbs_name_key'] ) ) : '';
			$name_prefix_to_key = isset( $_POST['mbs_name_prefix_to_key'] ) ? sanitize_text_field( wp_unslash( $_POST['mbs_name_prefix_to_key'] ) ) : '';
			$name_before_key    = isset( $_POST['mbs_name_before_key'] ) ? sanitize_text_field( wp_unslash( $_POST['mbs_name_before_key'] ) ) : '';
			$name_after_key     = isset( $_POST['mbs_name_after_key'] ) ? sanitize_text_field( wp_unslash( $_POST['mbs_name_after_key'] ) ) : '';
			if ( '' !== $name_key ) {
				$key_part      = trim( $name_prefix_to_key . ' ' . $name_key );
				$rest_parts    = array_filter( array( $name_before_key, $name_after_key ) );
				$rest          = implode( ' ', $rest_parts );
				$name_inverted = $rest ? $key_part . ', ' . $rest : $key_part;
			}
		}
		update_term_meta( $term_id, 'mbs_name_inverted', $name_inverted );

		// SHC-6: per-term layout override (PRO).
		if ( mbs_is_pro() && isset( $_POST['mbs_term_layout'] ) ) {
			$allowed = array_merge( array( '' ), MBS_Layout_Registry::get_all_layouts() );
			$layout  = sanitize_key( wp_unslash( $_POST['mbs_term_layout'] ) );
			if ( ! in_array( $layout, $allowed, true ) ) {
				$layout = '';
			}
			update_term_meta( $term_id, 'mbs_term_layout', $layout );
		}
	
	}
}
