<?php
/**
 * File Path: includes/export/class-mbs-book-bible-metabox.php
 *
 * Export Book Bible Metabox
 *
 * Side metabox on the book editor. Visible to all tiers.
 * Shows a completeness badge (field counter) and a tier-aware
 * download button. FREE users see the full counter but the
 * export button is replaced with an upgrade CTA.
 *
 * @package My_Book_Showroom
 * @since   2.5.0
 */

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

/**
 * Class MBS_Book_Bible_Metabox
 *
 * @since 2.5.0
 */
class MBS_Book_Bible_Metabox { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Constructor. Registers WP hooks.
	 *
	 * @since 2.5.0
	 */
	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'register' ) );
	}

	/**
	 * Register the Export Book Bible side metabox.
	 *
	 * @since 2.5.0
	 * @return void
	 */
	public function register(): void {
		add_meta_box(
			'mbs-export-book-bible',
			__( 'Export Book Bible', 'my-book-showroom' ),
			array( $this, 'render' ),
			MBS_POST_TYPE,
			'side',
			'default'
		);
	}

	/**
	 * Render the metabox.
	 *
	 * Completeness badge and score reflect the last saved state of the post.
	 * Button and below-button line vary by license tier.
	 *
	 * @param WP_Post $post Current post object.
	 * @since 2.5.0
	 * @return void
	 */
	public function render( WP_Post $post ): void {
		$result    = MBS_Book_Bible_Field_Counter::count( $post->ID );
		$populated = (int) $result['populated'];
		$possible  = (int) $result['possible'];
		$score     = $possible > 0 ? (int) round( $populated / $possible * 100 ) : 0;

		// Badge color and status message by threshold.
		if ( $score <= 60 ) {
			$badge_bg  = '#dc3232';
			$badge_txt = '#fff';
			$status    = __( 'Export not recommended — too many fields missing', 'my-book-showroom' );
		} elseif ( $score <= 90 ) {
			$badge_bg  = '#ffb900';
			$badge_txt = '#1d2327';
			$status    = __( 'Book data incomplete — consider adding more before exporting', 'my-book-showroom' );
		} else {
			$badge_bg  = '#46b450';
			$badge_txt = '#fff';
			$status    = '';
		}

		$is_pro = mbs_is_pro();
		$is_pub = mbs_is_pub();

		// AJAX export URL (built only when user can export).
		$export_url     = '';
		$upgrade_pro_url = add_query_arg( 'tier', 'pro', MBS_UPGRADE_URL );
		$upgrade_pub_url = add_query_arg( 'tier', 'pub', MBS_UPGRADE_URL );
		if ( $is_pro ) {
			$export_url = add_query_arg(
				array(
					'action'  => 'mbs_export_book_bible',
					'post_id' => $post->ID,
					'nonce'   => wp_create_nonce( 'mbs_export_book_bible' ),
				),
				admin_url( 'admin-ajax.php' )
			);
		}
		?>
		<p style="font-size:12px;color:#50575e;margin:0 0 10px;">
			<?php esc_html_e( 'The Book Bible is a comprehensive, print-ready XLSX workbook containing everything about your book in one place — publication data, marketing copy, classification codes, contributor details, format and retail information, and production notes. It is the single source of truth for your title, and the most complete snapshot of your book record that My Book Showroom can produce. The more you fill in, the more powerful it becomes.', 'my-book-showroom' ); ?>
		</p>

		<div style="display:flex;align-items:center;gap:8px;margin:0 0 6px;">
			<span style="display:inline-block;background:<?php echo esc_attr( $badge_bg ); ?>;color:<?php echo esc_attr( $badge_txt ); ?>;border-radius:3px;padding:3px 8px;font-size:13px;font-weight:600;white-space:nowrap;">
				<?php echo esc_html( $score . '%' ); ?>
			</span>
			<span style="font-size:12px;color:#50575e;">
				<?php
				printf(
					/* translators: 1: populated count, 2: possible count */
					esc_html__( '%1$d of %2$d fields populated', 'my-book-showroom' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_html__() escapes format string; integer args are safe with %d
					$populated, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- integer field count
					$possible // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- integer field count
				);
				?>
			</span>
		</div>

		<?php if ( '' !== $status ) : ?>
			<p style="font-size:11px;color:<?php echo esc_attr( $badge_bg ); ?>;margin:0 0 10px;font-style:italic;">
				<?php echo esc_html( $status ); ?>
			</p>
		<?php endif; ?>

		<div style="margin-top:10px;">
			<?php if ( $is_pro ) : ?>
				<a href="<?php echo esc_url( $export_url ); ?>"
				   class="button button-primary"
				   style="width:100%;text-align:center;box-sizing:border-box;">
					<?php esc_html_e( 'Download Book Bible', 'my-book-showroom' ); ?>
				</a>
				<?php if ( $is_pub ) : ?>
					<p style="font-size:11px;margin:6px 0 0;">
						<span class="dashicons dashicons-yes-alt" style="color:#46b450;font-size:14px;width:14px;height:14px;vertical-align:middle;"></span>
						<span style="color:#46b450;">
							<?php esc_html_e( 'Includes Copyright Page &amp; EPUB Metadata tabs', 'my-book-showroom' ); ?>
						</span>
					</p>
				<?php else : ?>
					<p style="font-size:11px;color:#72777c;margin:6px 0 0;">
						<span class="dashicons dashicons-lock" style="font-size:14px;width:14px;height:14px;vertical-align:middle;"></span>
						<a href="<?php echo esc_url( $upgrade_pub_url ); ?>"
						   style="color:inherit;text-decoration:none;"
						   target="_blank" rel="noopener noreferrer">
							<?php esc_html_e( 'Upgrade to PUB for Copyright Page &amp; EPUB Metadata tabs', 'my-book-showroom' ); ?>
						</a>
					</p>
				<?php endif; ?>
			<?php else : ?>
				<a href="<?php echo esc_url( $upgrade_pro_url ); ?>"
				   class="button button-secondary"
				   style="width:100%;text-align:center;box-sizing:border-box;"
				   target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Upgrade to PRO to Export', 'my-book-showroom' ); ?>
				</a>
			<?php endif; ?>
		</div>

		<?php if ( $is_pro ) : ?>
		<!-- INSIGHTS-3: Press Kit generate button -->
		<?php
		$press_kit_url = add_query_arg(
			array(
				'action'  => 'mbs_generate_press_kit',
				'post_id' => $post->ID,
				'nonce'   => wp_create_nonce( 'mbs_generate_press_kit_' . $post->ID ),
			),
			admin_url( 'admin-ajax.php' )
		);
		?>
		<div style="margin-top:8px;padding-top:8px;border-top:1px solid #e0e0e0;">
			<a href="<?php echo esc_url( $press_kit_url ); ?>"
			   class="button"
			   style="width:100%;text-align:center;box-sizing:border-box;">
				<?php esc_html_e( 'Download Press Kit', 'my-book-showroom' ); ?>
			</a>
			<p style="font-size:11px;color:#72777c;margin:4px 0 0;">
				<?php esc_html_e( 'DOCX — title page, author bio, key facts', 'my-book-showroom' ); ?>
			</p>
		</div>
		<?php endif; ?>
		<?php
	}
}
