<?php
/**
 * File Path: includes/admin/tabs/authors-series/class-mbs-tab-authors-render.php
 *
 * Authors Tab — Render Class
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs/Authors-Series
 * @since      1.0.0
 */

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

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

	/**
	 * Render the Authors tab.
	 *
	 * Outputs the tab wrapper, the success notice (when redirected after save),
	 * and one <form>-wrapped <details> card per author term. The card whose
	 * term_id matches the 'saved' query arg auto-expands via the 'open'
	 * attribute so the admin lands focused on the row they just edited.
	 *
	 * @return void
	 */
	public static function render(): void {
		$updated  = isset( $_GET['updated'] ) && '1' === $_GET['updated']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$saved_id = isset( $_GET['saved'] ) ? absint( $_GET['saved'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		// F-SORT-2: Read per-user sort preference (default: first_name).
		$sort_pref = (string) get_user_meta( get_current_user_id(), 'mbs_sort_pref_authors', true );
		if ( ! in_array( $sort_pref, array( 'first_name', 'last_name' ), true ) ) {
			$sort_pref = 'first_name';
		}

		$authors = get_terms( array(
			'taxonomy'   => MBS_TAX_AUTHOR,
			'hide_empty' => false,
			'orderby'    => 'name',
			'order'      => 'ASC',
		) );

		// F-SORT-2: When sorting by last name, re-sort in PHP using mbs_name_key.
		if ( ! is_wp_error( $authors ) && ! empty( $authors ) && 'last_name' === $sort_pref ) {
			usort( $authors, static function ( $a, $b ) {
				$ka = (string) get_term_meta( $a->term_id, 'mbs_name_key', true );
				$kb = (string) get_term_meta( $b->term_id, 'mbs_name_key', true );
				if ( '' === $ka ) {
					// F-SORT-2 fallback: use last word of display name as surname when mbs_name_key not set.
					$_parts = explode( ' ', trim( $a->name ) );
					$ka     = function_exists( 'mb_strtolower' ) ? mb_strtolower( end( $_parts ) ) : strtolower( end( $_parts ) );
				}
				if ( '' === $kb ) {
					$_parts = explode( ' ', trim( $b->name ) );
					$kb     = function_exists( 'mb_strtolower' ) ? mb_strtolower( end( $_parts ) ) : strtolower( end( $_parts ) );
				}
				return strcmp( $ka, $kb );
			} );
		}

		// Group authors by first letter; non-alpha names go under '#'.
		// When sort is last_name, group by the first character of mbs_name_key.
		$grouped = array();
		if ( ! is_wp_error( $authors ) && ! empty( $authors ) ) {
			foreach ( $authors as $author ) {
				if ( 'last_name' === $sort_pref ) {
					$name_key = (string) get_term_meta( $author->term_id, 'mbs_name_key', true );
					if ( '' !== $name_key ) {
						$source = $name_key;
					} else {
						// F-SORT-2 fallback: no mbs_name_key -- use last word as surname initial.
						$_gp    = explode( ' ', trim( $author->name ) );
						$source = end( $_gp ) ?: $author->name;
					}
				} else {
					$source = $author->name;
				}
				$first = function_exists( 'mb_strtoupper' )
					? mb_strtoupper( mb_substr( $source, 0, 1 ) )
					: strtoupper( substr( $source, 0, 1 ) );
				$key               = ctype_alpha( $first ) ? $first : '#';
				$grouped[ $key ][] = $author;
			}
			ksort( $grouped );
			// Move '#' to the end if present.
			if ( isset( $grouped['#'] ) ) {
				$hash = $grouped['#'];
				unset( $grouped['#'] );
				$grouped['#'] = $hash;
			}
		}
		?>
		<div class="mbs-tab-authors">

			<?php MBS_Tab_Catalog_Subnav::render( 'authors' ); // UX-NAV-001 ?>

			<h2><?php esc_html_e( 'Authors', 'my-book-showroom' ); ?></h2>
			<p class="mbs-settings-subtitle">
				<?php esc_html_e( 'Extended profile fields for each author. Click a row to expand and edit.', 'my-book-showroom' ); ?>
				<a href="<?php echo esc_url( admin_url( 'edit-tags.php?taxonomy=' . MBS_TAX_AUTHOR . '&post_type=' . MBS_POST_TYPE ) ); ?>">
					<?php esc_html_e( 'Add / remove authors →', 'my-book-showroom' ); ?>
				</a>
			</p>

			<?php if ( $updated ) : ?>
				<div class="notice notice-success inline">
					<p><?php esc_html_e( 'Saved.', 'my-book-showroom' ); ?></p>
				</div>
			<?php endif; ?>

			<?php if ( empty( $grouped ) ) : ?>
				<div class="mbs-settings-card">
					<p><?php esc_html_e( 'No authors found. Add books with authors first.', 'my-book-showroom' ); ?></p>
				</div>
			<?php else : ?>

				<div class="mbs-list-toolbar">
					<input type="search"
					       class="mbs-list-filter-input"
					       placeholder="<?php esc_attr_e( 'Filter by name…', 'my-book-showroom' ); ?>"
					       aria-label="<?php esc_attr_e( 'Filter authors', 'my-book-showroom' ); ?>">
					<p class="description mbs-list-filter-hint">
						<?php esc_html_e( 'Type to filter the list. Results update instantly.', 'my-book-showroom' ); ?>
					</p>
					<div class="mbs-sort-toggle" role="group" aria-label="<?php esc_attr_e( 'Sort order', 'my-book-showroom' ); ?>">
						<span class="mbs-sort-toggle-label"><?php esc_html_e( 'Sort by:', 'my-book-showroom' ); ?></span>
						<button type="button"
						        class="button<?php echo 'first_name' === $sort_pref ? ' button-primary' : ''; ?>"
						        data-sort-pref="first_name"
						        <?php echo 'first_name' === $sort_pref ? 'aria-pressed="true"' : 'aria-pressed="false"'; ?>>
							<?php esc_html_e( 'First name', 'my-book-showroom' ); ?>
						</button>
						<button type="button"
						        class="button<?php echo 'last_name' === $sort_pref ? ' button-primary' : ''; ?>"
						        data-sort-pref="last_name"
						        <?php echo 'last_name' === $sort_pref ? 'aria-pressed="true"' : 'aria-pressed="false"'; ?>>
							<?php esc_html_e( 'Last name', 'my-book-showroom' ); ?>
						</button>
					</div>
					<div class="mbs-list-toolbar-actions">
						<button type="button" class="button mbs-expand-all">
							<?php esc_html_e( 'Expand all', 'my-book-showroom' ); ?>
						</button>
						<button type="button" class="button mbs-collapse-all">
							<?php esc_html_e( 'Collapse all', 'my-book-showroom' ); ?>
						</button>
					</div>
				</div>

				<div class="mbs-authors-card-list">
					<?php foreach ( $grouped as $letter => $letter_authors ) :
						// A letter group stays open by default. If it contains
						// the just-saved card it must also be open on page load.
					?>
						<details class="mbs-letter-group" open>
							<summary class="mbs-letter-group-summary">
								<span class="mbs-letter-group-label"><?php echo esc_html( $letter ); ?></span>
								<span class="mbs-letter-group-count">
									<?php /* translators: %d: number of authors in this letter group */ printf(
										esc_html( _n( '%d author', '%d authors', count( $letter_authors ), 'my-book-showroom' ) ),
										count( $letter_authors )
									); ?>
								</span>
							</summary>
							<div class="mbs-letter-group-body">
								<?php foreach ( $letter_authors as $author ) :
									self::render_author_card( $author, $saved_id );
								endforeach; ?>
							</div>
						</details>
					<?php endforeach; ?>

					<p class="mbs-filter-no-results" hidden>
						<?php esc_html_e( 'No authors match your search.', 'my-book-showroom' ); ?>
					</p>
				</div>

			<?php endif; ?>

		</div>
		<?php
	}

	/**
	 * Render a single author card via template.
	 *
	 * Prepares variables and delegates all HTML output to
	 * templates/admin/author-card.php, which internally loads
	 * templates/admin/author-photo-field.php for the photo picker.
	 *
	 * @param WP_Term $author   The author term.
	 * @param int     $saved_id The term_id from the 'saved' query arg (auto-expand target).
	 * @return void
	 */
	public static function render_author_card( $author, int $saved_id ): void {
		$term_id    = (int) $author->term_id;
		$photo_id   = (int) get_term_meta( $term_id, 'mbs_author_photo_id', true );
		$bio        = (string) get_term_meta( $term_id, 'mbs_author_bio', true );
		$website    = (string) get_term_meta( $term_id, 'mbs_author_website_url', true );
		$photo_url  = $photo_id ? (string) wp_get_attachment_image_url( $photo_id, array( 80, 80 ) ) : ''; // R5-exempt: admin series UI
		$book_count = (int) $author->count;
		$is_open      = ( $term_id === $saved_id );
		$initial      = function_exists( 'mb_substr' ) ? mb_substr( $author->name, 0, 1 ) : substr( $author->name, 0, 1 );
		$edit_url     = admin_url( 'edit-tags.php?action=edit&taxonomy=' . MBS_TAX_AUTHOR . '&tag_ID=' . $term_id . '&post_type=' . MBS_POST_TYPE );
		$is_featured         = (bool)   get_term_meta( $term_id, 'mbs_author_featured',   true );
		$name_titles_before  = (string) get_term_meta( $term_id, 'mbs_name_titles_before',  true );
		$name_before_key     = (string) get_term_meta( $term_id, 'mbs_name_before_key',     true );
		$name_prefix_to_key  = (string) get_term_meta( $term_id, 'mbs_name_prefix_to_key',  true );
		$name_key            = (string) get_term_meta( $term_id, 'mbs_name_key',            true );
		$name_after_key      = (string) get_term_meta( $term_id, 'mbs_name_after_key',      true );
		$name_letters        = (string) get_term_meta( $term_id, 'mbs_name_letters',        true );
		$name_inverted       = (string) get_term_meta( $term_id, 'mbs_name_inverted',       true );
		$birth_year          = (string) get_term_meta( $term_id, 'mbs_author_birth_year',   true );

		$term_layout = (string) get_term_meta( $term_id, 'mbs_term_layout', true );

		mbs_get_template_part( 'admin/author-card', array(
			'author'        => $author,
			'term_id'       => $term_id,
			'photo_id'      => $photo_id,
			'bio'           => $bio,
			'website'       => $website,
			'photo_url'     => $photo_url,
			'book_count'    => $book_count,
			'is_open'       => $is_open,
			'initial'       => $initial,
			'edit_url'      => $edit_url,
			'social_links' => MBS_Author_Social_Links::decode_social_links( $term_id ),
			'platforms'    => MBS_Author_Social_Links::PLATFORMS,
			'is_featured'        => $is_featured,
			'name_titles_before'  => $name_titles_before,
			'name_before_key'     => $name_before_key,
			'name_prefix_to_key'  => $name_prefix_to_key,
			'name_key'            => $name_key,
			'name_after_key'      => $name_after_key,
			'name_letters'        => $name_letters,
			'name_inverted'       => $name_inverted,
			'birth_year'          => $birth_year,
			'term_layout'         => $term_layout,
		) );
	}
}
