<?php
/**
 * File Path: includes/admin/class-mbs-onboarding-widget.php
 *
 * MBS Onboarding Checklist Dashboard Widget — Story 13-2
 *
 * Registers a WordPress admin dashboard widget titled
 * "My Book Showroom — Getting Started".
 *
 * Shows 5 checklist items with live ✓ / ○ state:
 *   ① First book added       — checks mbs_book post count
 *   ② Shortcode placed       — checks post_content of published pages
 *   ③ Registration (optional) — checks mbs_license_registered; never blocks auto-hide (WO-002)
 *   ④ Layout chosen          — checks mbs_setting_formatting_default_layout is non-default
 *   ⑤ Affiliate codes set    — PRO only; shows upgrade link on FREE
 *
 * Auto-hides when all required items are complete (optional items are skipped) OR when the user dismisses.
 * Dismissal stored in user_meta (per-user, not global).
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin
 * @since      1.0.0
 */

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

/**
 * Class MBS_Onboarding_Widget
 */
class MBS_Onboarding_Widget {

	/** user_meta key for per-user dismissal. */
	const DISMISSED_META_KEY = 'mbs_onboarding_widget_dismissed';

	/** Widget ID used with wp_add_dashboard_widget(). */
	const WIDGET_ID = 'mbs_onboarding_checklist';

	public function __construct() {
		add_action( 'wp_dashboard_setup',             array( $this, 'register_widget' ) );
		add_action( 'wp_ajax_mbs_dismiss_onboarding', array( $this, 'ajax_dismiss' ) );
	}

	// -------------------------------------------------------------------------
	// Widget registration
	// -------------------------------------------------------------------------

	/**
	 * Register the dashboard widget.
	 * Skipped if the current user already dismissed it or all items are done.
	 */
	public function register_widget(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( get_user_meta( $user_id, self::DISMISSED_META_KEY, true ) ) {
			return;
		}

		$items = $this->get_checklist_items();
		if ( $this->all_complete( $items ) ) {
			return;
		}

		wp_add_dashboard_widget(
			self::WIDGET_ID,
			__( 'My Book Showroom — Getting Started', 'my-book-showroom' ),
			array( $this, 'render_widget' )
		);
	}

	// -------------------------------------------------------------------------
	// AJAX dismiss
	// -------------------------------------------------------------------------

	/**
	 * Handle the dismiss AJAX request (per-user via user_meta).
	 */
	public function ajax_dismiss(): void {
		check_ajax_referer( 'mbs_dismiss_onboarding', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Insufficient permissions.' ), 403 );
		}

		update_user_meta( get_current_user_id(), self::DISMISSED_META_KEY, '1' );
		wp_send_json_success();
	}

	// -------------------------------------------------------------------------
	// Checklist state
	// -------------------------------------------------------------------------

	/**
	 * Build the 5 checklist item definitions with live state.
	 *
	 * @return array[]  Each element: [ 'label' => string, 'done' => bool, 'pro_only' => bool, 'optional' => bool, 'link' => string, 'note' => string|null ]
	 */
	private function get_checklist_items(): array {
		return array(
			array(
				'label'    => __( 'Add your first book', 'my-book-showroom' ),
				'done'     => $this->check_book_exists(),
				'pro_only' => false,
				'link'     => admin_url( 'post-new.php?post_type=' . MBS_POST_TYPE ),
				'link_text'=> __( 'Add a book', 'my-book-showroom' ),
			),
			array(
				'label'    => __( 'Place the shortcode on a page', 'my-book-showroom' ),
				'done'     => $this->check_shortcode_placed(),
				'pro_only' => false,
				'link'     => admin_url( 'admin.php?page=my-book-showroom-settings&tab=shortcodes' ),
				'link_text'=> __( 'Get shortcodes', 'my-book-showroom' ),
			),
			array(
				'label'    => __( 'Register your plugin (optional)', 'my-book-showroom' ),
				'done'     => (bool) get_option( 'mbs_license_registered', false ),
				'pro_only' => false,
				'optional' => true, // WO-002: non-blocking; widget auto-hides without this step
				'link'     => admin_url( 'admin.php?page=my-book-showroom-settings&tab=license' ),
				'link_text'=> __( 'Register your plugin →', 'my-book-showroom' ),
				'note'     => '<a href="' . esc_url( MBS_PRIVACY_URL ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Privacy policy', 'my-book-showroom' ) . '</a>',
			),
			array(
				'label'    => __( 'Choose a display layout', 'my-book-showroom' ),
				'done'     => $this->check_layout_chosen(),
				'pro_only' => false,
				'link'     => admin_url( 'admin.php?page=my-book-showroom-settings&tab=formatting' ),
				'link_text'=> __( 'Choose layout', 'my-book-showroom' ),
			),
			array(
				'label'    => __( 'Set up affiliate codes', 'my-book-showroom' ),
				'done'     => $this->check_affiliate_set(),
				'pro_only' => true,
				'link'     => mbs_is_pro()
					? admin_url( 'admin.php?page=my-book-showroom-settings&tab=affiliate' )
					: 'https://mybookshowroom.com/upgrade/',
				'link_text'=> mbs_is_pro()
					? __( 'Set up affiliates', 'my-book-showroom' )
					: __( 'Upgrade to PRO', 'my-book-showroom' ),
			),
		);
	}

	/**
	 * Returns true when all required items are done.
	 * PRO items are skipped on FREE; optional items are always skipped (WO-002).
	 *
	 * @param array[]|null $items Pre-built items array, or null to build fresh.
	 * @return bool
	 */
	private function all_complete( ?array $items = null ): bool {
		if ( null === $items ) {
			$items = $this->get_checklist_items();
		}

		foreach ( $items as $item ) {
			// PRO items are treated as N/A on FREE — don't block completion.
			if ( $item['pro_only'] && ! mbs_is_pro() ) {
				continue;
			}
			// Optional items (e.g. registration) never block auto-completion (WO-002).
			if ( ! empty( $item['optional'] ) ) {
				continue;
			}
			if ( ! $item['done'] ) {
				return false;
			}
		}

		return true;
	}

	// ── Individual checks ────────────────────────────────────────────────────

	/** True when at least one mbs_book post exists (any status). */
	private function check_book_exists(): bool {
		$counts = wp_count_posts( MBS_POST_TYPE );
		return (
			(int) ( $counts->publish ?? 0 ) +
			(int) ( $counts->draft   ?? 0 ) +
			(int) ( $counts->private ?? 0 )
		) > 0;
	}

	/** True when any published page contains an [mbs_books] or [mbs_book] shortcode. */
	private function check_shortcode_placed(): bool {
		return MBS_Book_Query::check_shortcode_placed();
	}

	/** True when the default layout has been changed from the factory default ('hero'). */
	private function check_layout_chosen(): bool {
		$saved = get_option( 'mbs_setting_formatting_default_layout', '' );
		// Factory default from DEVELOPER-REFERENCE §2 (Phase 4c): 'hero'.
		// The user has actively chosen when any non-empty value is stored.
		return ! empty( $saved ) && 'hero' !== $saved;
	}

	/** True when at least one affiliate code (Amazon tag) has been saved. */
	private function check_affiliate_set(): bool {
		if ( ! mbs_is_pro() ) {
			return false;
		}
		$tag = get_option( 'mbs_setting_affiliate_amazon_tag', '' );
		return ! empty( $tag );
	}

	// -------------------------------------------------------------------------
	// Widget render
	// -------------------------------------------------------------------------

	/**
	 * Render the dashboard widget HTML.
	 */
	public function render_widget(): void {
		$items   = $this->get_checklist_items();
		$nonce   = wp_create_nonce( 'mbs_dismiss_onboarding' );
		$all_done = $this->all_complete( $items );

		wp_enqueue_style(
			'mbs-admin',
			MBS_ASSETS_URL . 'css/mbs-admin.css',
			array(),
			MBS_VERSION
		);

		?>
		<div class="mbs-onboarding-widget <?php echo $all_done ? 'mbs-onboarding-complete' : ''; ?>">

			<?php if ( $all_done ) : ?>
				<p class="mbs-onboarding-done">
					&#10003; <?php esc_html_e( "You're all set! My Book Showroom is ready to go.", 'my-book-showroom' ); ?>
				</p>
			<?php else : ?>
				<ul class="mbs-onboarding-list">
					<?php foreach ( $items as $item ) :
						$is_pro_locked = $item['pro_only'] && ! mbs_is_pro();
					?>
						<?php $is_optional = ! empty( $item['optional'] ); ?>
						<li class="mbs-onboarding-item <?php echo $item['done'] ? 'done' : ''; ?> <?php echo $is_pro_locked ? 'pro-locked' : ''; ?> <?php echo $is_optional ? 'mbs-optional-step' : ''; ?>">
							<span class="mbs-onboarding-check">
								<?php echo $item['done'] ? '&#10003;' : '&#9711;'; ?>
							</span>
							<span class="mbs-onboarding-label">
								<?php echo esc_html( $item['label'] ); ?>
								<?php if ( $is_pro_locked ) : ?>
									<span class="mbs-pro-badge">PRO</span>
								<?php endif; ?>
							</span>
							<?php if ( ! $item['done'] ) : ?>
								<a href="<?php echo esc_url( $item['link'] ); ?>"
								   class="mbs-onboarding-action"
								   <?php echo $is_pro_locked ? 'target="_blank" rel="noopener"' : ''; ?>>
									<?php echo esc_html( $item['link_text'] ); ?>
								</a>
							<?php endif; ?>
							<?php if ( ! empty( $item['note'] ) ) : ?>
								<span class="mbs-onboarding-note"><?php echo wp_kses_post( $item['note'] ); ?></span>
							<?php endif; ?>
						</li>
					<?php endforeach; ?>
				</ul>
			<?php endif; ?>

			<p class="mbs-onboarding-dismiss-row">
				<button type="button" class="button-link mbs-onboarding-dismiss-btn">
					<?php esc_html_e( 'Dismiss this widget', 'my-book-showroom' ); ?>
				</button>
			</p>

		</div>

		<script>
		(function($){
			$('.mbs-onboarding-dismiss-btn').on('click', function(){
				$.post(ajaxurl, {
					action: 'mbs_dismiss_onboarding',
					nonce:  <?php echo wp_json_encode( $nonce ); ?>
				}, function(){
					$('#' + <?php echo wp_json_encode( self::WIDGET_ID ); ?>).fadeOut(300, function(){ $(this).remove(); });
				});
			});
		})(jQuery);
		</script>
		<?php
	}
}
