<?php
/**
 * File Path: /includes/metaboxes/book-header/class-mbs-book-header-cover.php
 *
 * Book Header Child Section - Cover
 *
 * Handles Book Default Cover upload, preview, replace, and remove (with full JS).
 *
 * CSS classes introduced (all defined in mbs-admin-settings.css):
 *   .mbs-cover-preview   — margin-bottom:10px on the preview container div
 *   .mbs-cover-remove    — margin-left:8px on the Remove button
 *
 * @subpackage Includes/Metaboxes/BookHeader
 */

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

/**
 * Class MBS_Book_Header_Cover
 */
// 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_Cover { // 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_cover', array( $this, 'render' ) );
        add_action( 'mbs_book_header_save_cover', array( $this, 'save' ), 10, 2 );
    }

    public function render( $post ) {
        $cover_id = get_post_thumbnail_id( $post->ID ); // R5-exempt: cover upload/admin context

        // PRO video fields.
        $is_pro               = mbs_is_pro();
        $spinning_video_id    = (int) get_post_meta( $post->ID, 'mbs_spinning_video_id', true );
        $spinning_video_title = $spinning_video_id ? get_the_title( $spinning_video_id ) : '';
        $trailer_video_id     = (int) get_post_meta( $post->ID, 'mbs_trailer_video_id', true );
        $trailer_video_title  = $trailer_video_id ? get_the_title( $trailer_video_id ) : '';
        $trailer_embed_url    = get_post_meta( $post->ID, 'mbs_trailer_embed_url', true );

        ?>
        <!-- Book Default Cover -->
        <tr>
            <th scope="row">
                <label for="mbs_cover"><?php esc_html_e( 'Book Default Cover', 'my-book-showroom' ); ?></label>
            </th>
            <td>
                <input type="hidden" id="mbs_cover_id" name="_thumbnail_id" value="<?php echo esc_attr( $cover_id ); ?>" />
                <div id="mbs-cover-preview" class="mbs-cover-preview">
                    <?php if ( $cover_id ) : ?>
                        <?php echo wp_get_attachment_image( $cover_id, 'medium', false, array( 'style' => 'max-width:110px;height:auto;' ) ); ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="button" id="mbs-cover-upload"><?php echo $cover_id ? esc_html__( 'Replace Cover', 'my-book-showroom' ) : esc_html__( 'Upload Cover', 'my-book-showroom' ); ?></button>
                <?php if ( $cover_id ) : ?>
                    <button type="button" class="button button-link-delete mbs-cover-remove" id="mbs-cover-remove"><?php esc_html_e( 'Remove', 'my-book-showroom' ); ?></button>
                <?php endif; ?>
                <p class="description"><?php esc_html_e( 'Recommended: 1600×2560 px JPEG (portrait). For audiobook format rows, use a separate square cover (3000×3000 px) on the format row below.', 'my-book-showroom' ); ?></p>
            </td>
        </tr>

        <?php if ( $is_pro ) : ?>

        <!-- Spinning Book Video (Fallback) — PRO -->
        <tr>
            <th scope="row">
                <label for="mbs_spinning_video_id"><?php esc_html_e( 'Spinning Book Video', 'my-book-showroom' ); ?></label>
            </th>
            <td>
                <div class="mbs-video-uploader">
                    <input type="hidden" id="mbs_book_spinning_video_id" name="mbs_book_spinning_video_id"
                           value="<?php echo esc_attr( $spinning_video_id ?: '' ); ?>">
                    <span class="mbs-video-filename"<?php echo $spinning_video_id ? '' : ' style="display:none;"'; ?>>
                        <?php echo esc_html( $spinning_video_title ); ?>
                    </span>
                    <button type="button" class="button mbs-upload-video-btn" data-field="mbs_book_spinning_video_id">
                        <?php echo $spinning_video_id ? esc_html__( 'Replace Video', 'my-book-showroom' ) : esc_html__( 'Upload Video', 'my-book-showroom' ); ?>
                    </button>
                    <button type="button" class="button button-link-delete mbs-remove-video-btn"
                            data-field="mbs_book_spinning_video_id"<?php echo $spinning_video_id ? '' : ' style="display:none;"'; ?>>
                        <?php esc_html_e( 'Remove', 'my-book-showroom' ); ?>
                    </button>
                    <p class="description"><?php esc_html_e( 'MP4 recommended. Shown as the animated cover fallback when a format row has no spinning video of its own.', 'my-book-showroom' ); ?></p>
                </div>
            </td>
        </tr>

        <!-- Book Trailer — PRO -->
        <tr>
            <th scope="row">
                <label for="mbs_trailer_video_id"><?php esc_html_e( 'Book Trailer', 'my-book-showroom' ); ?></label>
            </th>
            <td>
                <div class="mbs-video-uploader">
                    <input type="hidden" id="mbs_trailer_video_id" name="mbs_trailer_video_id"
                           value="<?php echo esc_attr( $trailer_video_id ?: '' ); ?>">
                    <span class="mbs-video-filename"<?php echo $trailer_video_id ? '' : ' style="display:none;"'; ?>>
                        <?php echo esc_html( $trailer_video_title ); ?>
                    </span>
                    <button type="button" class="button mbs-upload-video-btn" data-field="mbs_trailer_video_id">
                        <?php echo $trailer_video_id ? esc_html__( 'Replace Trailer', 'my-book-showroom' ) : esc_html__( 'Upload Trailer', 'my-book-showroom' ); ?>
                    </button>
                    <button type="button" class="button button-link-delete mbs-remove-video-btn"
                            data-field="mbs_trailer_video_id"<?php echo $trailer_video_id ? '' : ' style="display:none;"'; ?>>
                        <?php esc_html_e( 'Remove', 'my-book-showroom' ); ?>
                    </button>
                </div>
                <div style="margin-top:6px;">
                    <input type="url" id="mbs_trailer_embed_url" name="mbs_trailer_embed_url"
                           class="large-text"
                           value="<?php echo esc_attr( $trailer_embed_url ); ?>"
                           placeholder="<?php esc_attr_e( 'Or paste a YouTube / Vimeo URL', 'my-book-showroom' ); ?>">
                    <p class="description"><?php esc_html_e( 'Upload a video file above, or paste an embed URL. The uploaded file takes priority if both are set.', 'my-book-showroom' ); ?></p>
                </div>
            </td>
        </tr>

        <?php else : ?>
            <!-- MBS: Spinning book video requires PRO license -->
            <!-- MBS: Book trailer requires PRO license -->
        <?php endif; ?>
        <?php
    }

    public function save( $post_id, $post ) {
        if ( isset( $_POST['_thumbnail_id'] ) ) {
            $cover_id = absint( wp_unslash( $_POST['_thumbnail_id'] ) ); // S-06: wp_unslash for consistency
            if ( $cover_id > 0 ) {
                if ( wp_attachment_is_image( $cover_id ) ) {
                    set_post_thumbnail( $post_id, $cover_id );
                }
                // If not a valid image attachment, leave existing thumbnail unchanged
            } else {
                delete_post_thumbnail( $post_id );
            }
        }

        // PRO video fields: gate DISPLAY on mbs_is_pro(), not storage.
        // Decoupling storage from mbs_is_pro() prevents data loss when the license ping
        // is temporarily stale between page-load and form-submit. The front-end renderer
        // already checks mbs_is_pro() independently before outputting the video.
        // Fields are only rendered (and therefore only appear in POST) when mbs_is_pro()
        // was true at render time, so a crafted-POST bypass is not possible.

        // Spinning Book Video fallback — attachment ID from media library.
        if ( isset( $_POST['mbs_book_spinning_video_id'] ) ) {
            $spinning_id = absint( wp_unslash( $_POST['mbs_book_spinning_video_id'] ) );
            if ( $spinning_id > 0 ) {
                update_post_meta( $post_id, 'mbs_spinning_video_id', $spinning_id );
            } elseif ( mbs_is_pro() ) {
                // Only delete when PRO confirmed — avoids wiping saved data on stale ping.
                delete_post_meta( $post_id, 'mbs_spinning_video_id' );
            }
        }

        // Book Trailer — uploaded video file attachment ID.
        if ( isset( $_POST['mbs_trailer_video_id'] ) ) {
            $trailer_id = absint( wp_unslash( $_POST['mbs_trailer_video_id'] ) );
            if ( $trailer_id > 0 ) {
                update_post_meta( $post_id, 'mbs_trailer_video_id', $trailer_id );
            } elseif ( mbs_is_pro() ) {
                delete_post_meta( $post_id, 'mbs_trailer_video_id' );
            }
        }

        // Book Trailer — embed URL fallback (YouTube / Vimeo).
        if ( isset( $_POST['mbs_trailer_embed_url'] ) ) {
            $trailer_url = esc_url_raw( trim( wp_unslash( $_POST['mbs_trailer_embed_url'] ) ) );
            update_post_meta( $post_id, 'mbs_trailer_embed_url', $trailer_url );
        }
    }
}
