<?php
/**
 * File Path: includes/admin/class-mbs-upgrade-nudge.php
 *
 * My Book Showroom — FREE-User Upgrade Nudge Notices
 *
 * Displays dismissible wp-admin notices at tenure milestones (30 / 90 / 180 / 270 / 365 days)
 * for FREE-tier users. Dismissal is stored per-user in user_meta so each admin
 * user controls their own notice state independently.
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

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

class MBS_Upgrade_Nudge extends MBS_Nudge_Base {

	/** wp_options key written by GC2-1. */
	const INSTALL_KEY = 'mbs_install_timestamp';

	/** user_meta key prefix — milestone slug appended, e.g. 'mbs_upgrade_nudge_dismissed_30d'. */
	const DISMISSED_META_PREFIX = 'mbs_upgrade_nudge_dismissed_';

	/** Upgrade page URL. */
	const UPGRADE_URL = 'https://mybookshowroom.com/upgrade/';

	/**
	 * Nonce action for the dismiss AJAX request.
	 *
	 * @return string
	 * @since 1.1.0
	 */
	protected function get_nonce_action(): string {
		return 'mbs_dismiss_upgrade_nudge';
	}

	public function __construct() {
		add_action( 'admin_notices', array( $this, 'maybe_show_notice' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_ajax_mbs_dismiss_upgrade_nudge', array( $this, 'handle_ajax_dismiss' ) );
	}

	/**
	 * Enqueue the dismiss-handler script on every admin page.
	 *
	 * The script is tiny and only binds to .mbs-upgrade-nudge elements; it is
	 * a no-op on pages where no nudge notice is rendered.
	 */
	public function enqueue_assets(): void {
		wp_enqueue_script(
			'mbs-upgrade-nudge',
			plugins_url( 'assets/js/adminjs/upgrade-nudge.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery' ),
			MBS_VERSION,
			true
		);
	}

	/**
	 * Milestone definitions — slug → days + copy.
	 *
	 * @return array<string, array{days: int, heading: string, body: string}>
	 */
	protected static function milestones(): array {
		return array(
			'30d'  => array(
				'days'    => 30,
				'heading' => __( 'You\'ve been using My Book Showroom for a month — thank you!', 'my-book-showroom' ),
				'body'    => __( 'Upgrade to PRO once and it\'s yours forever. No subscription, no ads, no data harvesting. Unlock scheduled releases, affiliate links, geo-redirects, and more.', 'my-book-showroom' ),
			),
			'90d'  => array(
				'days'    => 90,
				'heading' => __( 'Three months with My Book Showroom — we\'re glad you\'re here.', 'my-book-showroom' ),
				'body'    => __( 'PRO is a one-time purchase. Pay once, own it forever — no recurring fees, no ads, no strings. Get affiliate links, multi-marketplace buy buttons, and priority support.', 'my-book-showroom' ),
			),
			'180d' => array(
				'days'    => 180,
				'heading' => __( 'Six months on FREE — ready to go PRO?', 'my-book-showroom' ),
				'body'    => __( 'One payment and PRO is yours for life. No subscription ever. No ads. We respect your privacy. Get scheduled releases, advanced layouts, and priority support.', 'my-book-showroom' ),
			),
			'270d' => array(
				'days'    => 270,
				'heading' => __( 'Still on FREE after nine months? That\'s commitment.', 'my-book-showroom' ),
				'body'    => __( 'PRO is a one-time purchase — yours forever, no subscription, no ads, complete privacy. Unlock the full toolkit: affiliate rewriting, geo-redirects, scheduled releases, and more.', 'my-book-showroom' ),
			),
			'365d' => array(
				'days'    => 365,
				'heading' => __( 'One year with My Book Showroom — thank you!', 'my-book-showroom' ),
				'body'    => __( 'Celebrate with an upgrade. PRO is a one-time payment, yours forever. No subscription. No ads. Ever. We respect your privacy. Everything serious authors need to sell more books.', 'my-book-showroom' ),
			),
		);
	}

	/**
	 * Show the highest applicable milestone notice if all guards pass.
	 */
	public function maybe_show_notice(): void {
		// Guard 1 — admin + capability check.
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Guard 2 — PRO users never see upgrade nudges.
		if ( mbs_is_pro() ) {
			return;
		}

		// Guard 3 — wait until onboarding is complete (same gate as MBS_Telemetry).
		if ( get_option( 'mbs_setup_wizard_dismissed' ) !== '1' ) {
			return;
		}

		// Guard 4 — timestamp must be recorded (pre-GC2-1 installs have no value).
		$install_ts = (int) get_option( self::INSTALL_KEY );
		if ( $install_ts <= 0 ) {
			return;
		}

		$days_active = (int) floor( ( time() - $install_ts ) / DAY_IN_SECONDS );

		// Iterate milestones highest-first so the most advanced milestone wins.
		$milestones = array_reverse( self::milestones(), true );

		foreach ( $milestones as $slug => $milestone ) {
			// Skip — milestone not yet reached.
			if ( $days_active < $milestone['days'] ) {
				continue;
			}

			// Skip — this user already dismissed this milestone.
			if ( get_user_meta( get_current_user_id(), self::DISMISSED_META_PREFIX . $slug, true ) ) {
				continue;
			}

			// Render — one notice per page load, then stop.
			$this->render_notice( $slug, $milestone );
			return;
		}
	}

	/**
	 * Render a single upgrade nudge notice.
	 *
	 * @param string                            $slug      Milestone slug, e.g. '30d'.
	 * @param array{days:int,heading:string,body:string} $milestone Milestone definition.
	 */
	private function render_notice( string $slug, array $milestone ): void {
		$nonce = wp_create_nonce( 'mbs_dismiss_upgrade_nudge' );
		?>
		<div class="notice notice-info is-dismissible mbs-upgrade-nudge"
		     id="mbs-upgrade-nudge-<?php echo esc_attr( $slug ); ?>"
		     data-nonce="<?php echo esc_attr( $nonce ); ?>"
		     data-milestone="<?php echo esc_attr( $slug ); ?>"
		     style="padding: 12px 16px;">
			<p>
				<strong><?php echo esc_html( $milestone['heading'] ); ?></strong>
			</p>
			<p><?php echo esc_html( $milestone['body'] ); ?></p>
			<p>
				<a href="<?php echo esc_url( self::UPGRADE_URL ); ?>"
				   class="button button-primary"
				   target="_blank"
				   rel="noopener noreferrer">
					<?php esc_html_e( 'Upgrade to PRO', 'my-book-showroom' ); ?>
				</a>
				<button type="button"
				        class="button button-secondary mbs-nudge-dismiss-btn"
				        style="margin-left: 8px;">
					<?php esc_html_e( 'Remind me later', 'my-book-showroom' ); ?>
				</button>
			</p>
		</div>
		<?php
	}

}
