<?php
/**
 * File Path: includes/metaboxes/book-header/class-mbs-book-header-core-save.php
 *
 * Book Header Child Section — Core Fields Save Class
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Metaboxes/BookHeader
 * @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
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- input sanitized at point of use (sanitize_text_field, absint, wp_kses_post, etc.); false positives from PHPCS not tracing sanitization helpers called before this method
class MBS_Book_Header_Core_Save {

    /**
     * Register the wp_insert_post_data filter for title sync.
     * Moved from MBS_Plugin::load_admin() — REFACTOR-PLAN-ARCH-001 Batch D.
     */
    public static function register_hooks(): void {
        add_filter( 'wp_insert_post_data', array( __CLASS__, 'sync_title_to_post' ), 10, 2 );
    }

    /**
     * D-5: Write mbs_book_title into post_title during any mbs_book save.
     * Safe to read $_POST here — this filter only acts when $_POST['mbs_book_title']
     * is present (i.e., a real form submission), and sanitises before use.
     *
     * @param array $data    Sanitised post data about to be written to wp_posts.
     * @param array $postarr Raw post array (unused beyond type guard).
     * @return array Modified $data.
     */
    public static function sync_title_to_post( array $data, array $postarr ): array {
        if ( $data['post_type'] !== MBS_POST_TYPE ) {
            return $data;
        }
        if ( isset( $_POST['mbs_book_title'] ) ) {
            $title = sanitize_text_field( wp_unslash( $_POST['mbs_book_title'] ) );
            if ( '' !== $title ) {
                $data['post_title'] = $title;
            }
        }
        return $data;
    }

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

        // N-01: Persist PRO fields that are read via get_post_meta in tab-trailer.php and section-social-share.php
        // N-02: Use sanitize_textarea_field for textarea fields (preserves newlines for wp_kses_post rendering)
        // N-03: Apply wp_unslash to all $_POST reads for consistency with other metabox handlers
        $fields = array(
            'mbs_book_title',
            'mbs_tagline',
            'mbs_teaser',
            // mbs_trailer_embed_url moved to MBS_Book_Header_Cover::save() — render and save both live there.
            'mbs_share_text',
        );

        foreach ( $fields as $field ) {
            if ( isset( $_POST[ $field ] ) ) {
                $raw_value = wp_unslash( $_POST[ $field ] );
                $value     = ( 'mbs_teaser' === $field )
                    ? sanitize_textarea_field( $raw_value )
                    : sanitize_text_field( $raw_value );
                update_post_meta( $post_id, $field, $value );
            } else {
                delete_post_meta( $post_id, $field );
            }
        }

        // Back Cover / Flap Copy — PRO only (mbs_synopsis, ONIX TextType 23).
        if ( mbs_is_pro() ) {
            if ( isset( $_POST['mbs_synopsis'] ) ) {
                update_post_meta( $post_id, 'mbs_synopsis', sanitize_textarea_field( wp_unslash( $_POST['mbs_synopsis'] ) ) );
            } else {
                delete_post_meta( $post_id, 'mbs_synopsis' );
            }
        } else {
            delete_post_meta( $post_id, 'mbs_synopsis' );
        }

        // Publisher URL requires URL sanitization — handled separately from the text-field loop above.
        if ( isset( $_POST['mbs_publisher_url'] ) ) {
            $pub_url = esc_url_raw( wp_unslash( $_POST['mbs_publisher_url'] ) );
            if ( '' !== $pub_url ) {
                update_post_meta( $post_id, 'mbs_publisher_url', $pub_url );
            } else {
                delete_post_meta( $post_id, 'mbs_publisher_url' );
            }
        } else {
            delete_post_meta( $post_id, 'mbs_publisher_url' );
        }
    }
}
