<?php
/**
 * File Path: /includes/metaboxes/book-header/class-mbs-book-header-authors.php
 *
 * Book Header Child Section - Authors
 *
 * Handles Author(s) field only (render + save + JS).
 * Restores the exact previously working behavior (real names in tags, autocomplete ready).
 *
 * CSS classes introduced (all defined in mbs-admin-settings.css):
 *   .mbs-author-list   — margin-top:10px; min-height:32px; line-height:1.8 on the tag list div
 *
 * @subpackage Includes/Metaboxes/BookHeader
 */

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

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

    public function __construct() {
        add_action( 'mbs_book_header_render_authors', array( $this, 'render' ) );
        add_action( 'mbs_book_header_save_authors', array( $this, 'save' ), 10, 2 );
    }

    public function render( $post ) {
        // BUG-07C: Was using data-term-id (mismatched with JS data('term-name') reader)
        // and storing IDs in hidden field (mismatched with save handler that now accepts names).
        // Now uses term names consistently in both tag attributes and hidden field.
        $author_terms   = wp_get_post_terms( $post->ID, 'mbs_author', array( 'fields' => 'all' ) );
        $author_display = '';
        $author_names   = array();
        if ( ! is_wp_error( $author_terms ) ) {
            foreach ( $author_terms as $term ) {
                $author_display .= '<span class="mbs-author-tag" data-term-name="' . esc_attr( $term->name ) . '">'
                                . esc_html( $term->name )
                                . ' <a href="#" class="mbs-remove-author" title="Remove author">×</a></span> ';
                $author_names[] = $term->name;
            }
        }

        // Allowed HTML for the pre-built author tag list.
        // Each value was escaped at construction time above; wp_kses() provides
        // defense-in-depth at the point of output per SECURITY.md Rule 4.
        $allowed_author_html = array(
            'span' => array( 'class' => array(), 'data-term-name' => array() ),
            'a'    => array( 'href' => array(), 'class' => array(), 'title' => array() ),
        );

        ?>
        <!-- Author(s) Field -->
        <tr>
            <th scope="row">
                <label for="mbs_authors"><?php esc_html_e( 'Author(s)', 'my-book-showroom' ); ?></label>
            </th>
            <td>
                <input type="text" id="mbs_authors_input" class="regular-text" value="" placeholder="<?php esc_attr_e( 'Type to search authors...', 'my-book-showroom' ); ?>" style="width: 70%;" />
                <input type="hidden" id="mbs_authors" name="mbs_authors" value="<?php echo esc_attr( implode( ',', $author_names ) ); ?>" />
                <button type="button" class="button" id="mbs-add-author-btn"><?php esc_html_e( 'Add Author', 'my-book-showroom' ); ?></button>

                <div id="mbs-author-list" class="mbs-author-list">
                    <?php echo wp_kses( $author_display, $allowed_author_html ); ?>
                </div>
            </td>
        </tr>
        <?php
    }

    public function save( $post_id, $post ) {
        if ( isset( $_POST['mbs_authors'] ) ) {
            $author_input = sanitize_text_field( wp_unslash( $_POST['mbs_authors'] ) );
            // BUG-07D: Was doing absint() on every entry, converting term names to 0
            // and filtering them out — new authors typed in the field were always lost.
            // wp_set_post_terms() accepts term names; WordPress will find existing terms
            // or create new ones as needed. Pass raw trimmed strings directly.
            $author_names = array_values( array_filter( array_map( 'trim', explode( ',', $author_input ) ) ) );
            wp_set_post_terms( $post_id, $author_names, 'mbs_author' );
        } else {
            wp_set_post_terms( $post_id, array(), 'mbs_author' );
        }
    }
}
