<?php
/**
 * File Path: includes/metaboxes/book-header/class-mbs-book-header-notes.php
 *
 * Book Header Child Section - Notes
 *
 * Handles the Admin Notes field (internal notes, FREE), the Share This Book
 * on/off toggle (FREE, mbs_share_section_enabled), and the Social Share
 * Text override (PRO-only per F-004).
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Metaboxes/BookHeader
 * @since      1.0.0
 */

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

/**
 * Class MBS_Book_Header_Notes
 */
// 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_Notes { // 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_notes', array( $this, 'render' ) );
        add_action( 'mbs_book_header_save_notes',   array( $this, 'save' ), 10, 2 );
    }

    public function render( $post ) {
        $admin_notes    = get_post_meta( $post->ID, '_mbs_admin_notes', true );
        $share_text     = get_post_meta( $post->ID, 'mbs_share_text', true );
        $share_enabled  = get_post_meta( $post->ID, 'mbs_share_section_enabled', true );
        // Default ON when meta not yet set (empty string).
        $share_is_on    = ( '' === $share_enabled || '1' === (string) $share_enabled );

        $is_pro = mbs_is_pro();

        // --- Social Share Text preview data (PRO only) ---
        if ( $is_pro ) {
            $author_terms = wp_get_post_terms( $post->ID, 'mbs_author', array( 'fields' => 'names' ) );
            $author_names = ( ! is_wp_error( $author_terms ) && ! empty( $author_terms ) ) ? $author_terms : array();
            $author_count = count( $author_names );
            if ( $author_count === 0 ) {
                $first_author = '';
            } elseif ( $author_count === 1 ) {
                $first_author = $author_names[0];
            } elseif ( $author_count === 2 ) {
                $first_author = $author_names[0] . ' and ' . $author_names[1];
            } else {
                $last         = array_pop( $author_names );
                $first_author = implode( ', ', $author_names ) . ', and ' . $last;
            }
            $global_default = get_option(
                'mbs_setting_formatting_share_text',
                __( 'Check out "{title}" by {author} — {url}', 'my-book-showroom' )
            );

            wp_localize_script(
                'mbs-admin-share-text',
                'MBS_ShareTextData',
                array(
                    'title'         => get_the_title( $post->ID ),
                    'author'        => $first_author,
                    'url'           => get_permalink( $post->ID ),
                    'globalDefault' => $global_default,
                )
            );
        }
        ?>
        <tr>
            <th scope="row">
                <?php esc_html_e( 'Share This Book', 'my-book-showroom' ); ?>
                <span style="display:block; font-weight:normal; font-size:11px; color:#646970; margin-top:2px;">
                    <?php esc_html_e( 'buttons on book pages', 'my-book-showroom' ); ?>
                </span>
            </th>
            <td>
                <?php /* On/off toggle — FREE tier, controls mbs_share_section_enabled */ ?>
                <fieldset style="margin-bottom:12px; padding:10px 12px; border:1px solid #ddd; border-radius:4px; background:#f9f9f9;">
                    <label style="display:flex; align-items:center; gap:8px; font-weight:600; cursor:pointer;">
                        <input type="checkbox"
                               name="mbs_share_section_enabled"
                               value="1"
                               <?php checked( $share_is_on ); ?>>
                        <?php esc_html_e( 'Show “Share This Book” buttons on this book’s page', 'my-book-showroom' ); ?>
                    </label>
                    <p class="description" style="margin:6px 0 0 24px;">
                        <?php esc_html_e( 'Displays Facebook, email, and other share buttons so readers can share this book. Uncheck to hide the section for this title.', 'my-book-showroom' ); ?>
                    </p>
                </fieldset>

                <?php if ( $is_pro ) : ?>
                    <?php /* PRO: per-book share message override */ ?>
                    <p style="margin:0 0 6px; font-weight:600; font-size:13px;"><?php esc_html_e( 'Share Message (optional override)', 'my-book-showroom' ); ?></p>
                    <p class="description" style="margin-bottom:6px;">
                        <strong><?php esc_html_e( 'Global default:', 'my-book-showroom' ); ?></strong>
                        <span style="font-style:italic;"><?php echo esc_html( $global_default ); ?></span><br>
                        <?php esc_html_e( 'Leave the field below blank to use the global default above for this book.', 'my-book-showroom' ); ?>
                    </p>
                    <input type="text" id="mbs_share_text" name="mbs_share_text" class="large-text"
                           value="<?php echo esc_attr( $share_text ); ?>"
                           placeholder="<?php esc_attr_e( 'Leave blank to use the global default above', 'my-book-showroom' ); ?>">
                    <p class="description" style="margin-top:6px; margin-bottom:4px;">
                        <?php esc_html_e( 'Click a tag to insert it into the text above:', 'my-book-showroom' ); ?>
                    </p>
                    <div style="display:flex; gap:6px; flex-wrap:wrap; margin-bottom:8px;">
                        <button type="button" class="button mbs-share-text-pill" data-tag="{title}">+ {title}</button>
                        <button type="button" class="button mbs-share-text-pill" data-tag="{author}">+ {author}</button>
                        <button type="button" class="button mbs-share-text-pill" data-tag="{url}">+ {url}</button>
                    </div>
                    <p class="description">
                        <strong><?php esc_html_e( 'Preview:', 'my-book-showroom' ); ?></strong>
                        <span id="mbs_share_text_preview" style="font-style:italic;"></span>
                    </p>
                <?php else : ?>
                    <!-- MBS: per-book social share text override requires PRO license -->
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <th scope="row">
                <label for="mbs_admin_notes"><?php esc_html_e( 'Admin Notes (internal)', 'my-book-showroom' ); ?></label>
            </th>
            <td>
                <textarea id="mbs_admin_notes" name="mbs_admin_notes" rows="6" class="large-text"><?php echo esc_textarea( $admin_notes ); ?></textarea>
                <p class="description">
                    <?php esc_html_e( 'Private notes for editors and production staff — not visible on the front end.', 'my-book-showroom' ); ?>
                </p>
            </td>
        </tr>


        <?php
    }

    public function save( $post_id, $post ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        // Admin Notes — FREE.
        if ( isset( $_POST['mbs_admin_notes'] ) ) {
            $notes = wp_kses_post( wp_unslash( $_POST['mbs_admin_notes'] ) );
            update_post_meta( $post_id, '_mbs_admin_notes', $notes );
        }

        // Share section on/off toggle — FREE, all tiers.
        $share_enabled = isset( $_POST['mbs_share_section_enabled'] ) && '1' === $_POST['mbs_share_section_enabled'] ? '1' : '0';
        update_post_meta( $post_id, 'mbs_share_section_enabled', $share_enabled );

        // Social Share Text override — PRO only (F-004).
        if ( mbs_is_pro() ) {
            $share_text = isset( $_POST['mbs_share_text'] )
                ? sanitize_text_field( wp_unslash( $_POST['mbs_share_text'] ) )
                : '';
            update_post_meta( $post_id, 'mbs_share_text', $share_text );
        } else {
            delete_post_meta( $post_id, 'mbs_share_text' );
        }
    }
}
