<?php
/**
 * Admin notices and related AJAX actions.
 *
 * @package TrustLens\Admin
 * @since   1.1.5
 */

defined( 'ABSPATH' ) || exit;

/**
 * Handles promotional notices and dismissal actions.
 *
 * @since 1.1.5
 */
class TrustLens_Admin_Notices {

	private const REVIEW_NOTICE_DISMISSED_META      = 'trustlens_review_notice_dismissed';
	private const REVIEW_NOTICE_REMIND_LATER_META   = 'trustlens_review_notice_remind_later';
	private const REVIEW_NOTICE_MIN_DAYS_INSTALLED  = 7;
	private const REVIEW_NOTICE_MIN_CUSTOMERS       = 3;

	/**
	 * Minimum protected revenue (store currency) before the success-tier review
	 * notice celebrates a money-protected milestone. Keeps a trivial sub-unit
	 * figure from triggering the ask.
	 */
	private const REVIEW_NOTICE_REVENUE_FLOOR = 1.0;

	/**
	 * Transient that caches the computed protected-revenue figure, so the ROI
	 * query runs at most hourly instead of on every admin page load.
	 */
	private const REVIEW_REVENUE_TRANSIENT = 'trustlens_review_money_protected';

	/**
	 * How recent a blocked attack must be (in days) to still count as a fresh
	 * win for the success notice. Past this the attack tier stops firing, so a
	 * weeks-old attack never surfaces as a "just blocked" message.
	 */
	private const REVIEW_ATTACK_RECENCY_DAYS = 14;

	private const OPTIN_NOTICE_DISMISSED_META     = 'trustlens_optin_notice_dismissed';
	private const OPTIN_NOTICE_REMIND_LATER_META  = 'trustlens_optin_notice_remind_later';
	private const OPTIN_NOTICE_MIN_DAYS_INSTALLED = 7;
	private const OPTIN_NOTICE_MIN_CUSTOMERS      = 3;

	/**
	 * Register hooks.
	 *
	 * @since 1.1.5
	 * @return void
	 */
	public function register_hooks(): void {
		add_action( 'admin_notices', array( $this, 'render_promotional_notices' ) );
		add_action( 'wp_ajax_wstl_dismiss_review_notice', array( $this, 'ajax_dismiss_review_notice' ) );
		add_action( 'wp_ajax_wstl_remind_later_review_notice', array( $this, 'ajax_remind_later_review_notice' ) );
		add_action( 'wp_ajax_wstl_dismiss_optin_notice', array( $this, 'ajax_dismiss_optin_notice' ) );
		add_action( 'wp_ajax_wstl_remind_later_optin_notice', array( $this, 'ajax_remind_later_optin_notice' ) );
	}

	public function render_promotional_notices(): void {
		if ( ! $this->is_relevant_notice_screen() ) {
			return;
		}

		// At most one promotional notice per load. Opt-in recovery takes
		// priority over the review request; the review notice resumes once the
		// opt-in nudge is dismissed or the user opts in. The success-tier review
		// ask (a concrete win) takes priority over the time-based fallback, and
		// both share the same dismissal state so a user is never asked twice.
		if ( $this->maybe_render_optin_notice() ) {
			return;
		}

		if ( $this->maybe_render_success_review_notice() ) {
			return;
		}

		$this->maybe_render_review_notice();
	}

	private function is_relevant_notice_screen(): bool {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return false;
		}

		if ( 'plugins' === $screen->id ) {
			return true;
		}

		return strpos( $screen->id, 'trustlens' ) !== false;
	}

	private function maybe_render_review_notice(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

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

		$remind_later_until = (int) get_user_meta( $user_id, self::REVIEW_NOTICE_REMIND_LATER_META, true );
		if ( $remind_later_until > time() ) {
			return;
		}

		$installed_at = (int) get_option( 'trustlens_installed_timestamp', 0 );
		if ( $installed_at <= 0 ) {
			return;
		}

		$days_installed = (int) floor( ( time() - $installed_at ) / DAY_IN_SECONDS );
		if ( $days_installed < self::REVIEW_NOTICE_MIN_DAYS_INSTALLED ) {
			return;
		}

		$sync_status       = TrustLens_Historical_Sync::instance()->get_status();
		$engaged_customers = (int) ( $sync_status['total_customers'] ?? 0 );
		if ( $engaged_customers < self::REVIEW_NOTICE_MIN_CUSTOMERS ) {
			return;
		}

		$this->render_review_markup(
			esc_html__( 'Enjoying TrustLens?', 'trustlens' ),
			esc_html__( 'If TrustLens is helping you protect your store, a quick review helps other store owners find it — and means a lot to a small team.', 'trustlens' )
		);
	}

	/**
	 * Render the success-tier review request (a concrete win), if eligible.
	 *
	 * Takes priority over the time-based notice and shares its dismissal state,
	 * so a user is never asked twice. Fires on a genuine win without the 7-day
	 * gate the time tier requires.
	 *
	 * @since 1.3.2
	 * @return bool True if a notice was rendered.
	 */
	private function maybe_render_success_review_notice(): bool {
		$can_manage = current_user_can( 'manage_woocommerce' );
		if ( ! $can_manage ) {
			return false;
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return false;
		}

		$dismissed    = (bool) get_user_meta( $user_id, self::REVIEW_NOTICE_DISMISSED_META, true );
		$remind_until = (int) get_user_meta( $user_id, self::REVIEW_NOTICE_REMIND_LATER_META, true );

		$attack_at       = (int) get_option( TrustLens_Review_Events::ATTACK_OPTION, 0 );
		$attack_recorded = $attack_at > 0
			&& ( time() - $attack_at ) <= self::REVIEW_ATTACK_RECENCY_DAYS * DAY_IN_SECONDS;

		$money_protected = 0.0;
		$total_scored    = 0;
		$high_risk_count = 0;

		// Only run the heavier analytics/segment queries when the cheap gates
		// pass and no attack already qualifies, so a normal admin page load
		// doesn't pay for them once the user has dismissed or already qualifies.
		if ( ! $dismissed && $remind_until <= time() && ! $attack_recorded ) {
			$money_protected = $this->get_protected_revenue();

			$counts          = ( new TrustLens_Customer_Repository() )->get_segment_counts();
			$total_scored    = (int) array_sum( $counts );
			$high_risk_count = (int) ( ( $counts['risk'] ?? 0 ) + ( $counts['critical'] ?? 0 ) );
		}

		$tier = self::should_show_success_review_notice(
			$can_manage,
			$dismissed,
			$remind_until,
			time(),
			$attack_recorded,
			$money_protected,
			self::REVIEW_NOTICE_REVENUE_FLOOR,
			$total_scored,
			$high_risk_count,
			self::REVIEW_NOTICE_MIN_CUSTOMERS
		);

		if ( '' === $tier ) {
			return false;
		}

		list( $heading, $body ) = $this->success_notice_copy( $tier, $money_protected, $total_scored, $high_risk_count );
		$this->render_review_markup( $heading, $body );
		return true;
	}

	/**
	 * Protected-revenue figure for the success notice, cached so the ROI query
	 * (several DB reads) runs at most hourly rather than on every admin page load.
	 *
	 * @since 1.3.2
	 * @return float Protected revenue over the trailing window (store currency).
	 */
	private function get_protected_revenue(): float {
		$cached = get_transient( self::REVIEW_REVENUE_TRANSIENT );
		if ( false !== $cached ) {
			return (float) $cached;
		}

		$roi       = TrustLens_Analytics::get_roi_data( 30 );
		$protected = (float) ( $roi['money_protected']['total'] ?? 0 );

		set_transient( self::REVIEW_REVENUE_TRANSIENT, $protected, HOUR_IN_SECONDS );

		return $protected;
	}

	/**
	 * Pure decision: which success-tier review notice (if any) should render?
	 *
	 * All lookups are injected so this stays unit-testable. Priority when more
	 * than one trigger qualifies: a blocked attack, then protected revenue, then
	 * surfaced risk.
	 *
	 * @since 1.3.2
	 * @param bool  $can_manage      current_user_can( 'manage_woocommerce' ).
	 * @param bool  $dismissed       Review request permanently dismissed.
	 * @param int   $remind_until    Unix time until which the ask is snoozed.
	 * @param int   $now             Current Unix time.
	 * @param bool  $attack_recorded A card-testing attack has been blocked.
	 * @param float $money_protected Protected revenue over the window (store currency).
	 * @param float $revenue_floor   Minimum protected revenue to celebrate (0 disables).
	 * @param int   $total_scored    Total scored customers.
	 * @param int   $high_risk_count Customers in the Risk/Critical segments.
	 * @param int   $min_customers   Minimum scored customers for the risk tier.
	 * @return string 'attack' | 'revenue' | 'risk' | '' (none).
	 */
	public static function should_show_success_review_notice(
		bool $can_manage,
		bool $dismissed,
		int $remind_until,
		int $now,
		bool $attack_recorded,
		float $money_protected,
		float $revenue_floor,
		int $total_scored,
		int $high_risk_count,
		int $min_customers
	): string {
		if ( ! $can_manage ) {
			return '';
		}
		if ( $dismissed ) {
			return '';
		}
		if ( $remind_until > $now ) {
			return '';
		}
		if ( $attack_recorded ) {
			return 'attack';
		}
		if ( $revenue_floor > 0 && $money_protected >= $revenue_floor ) {
			return 'revenue';
		}
		if ( $total_scored >= $min_customers && $high_risk_count >= 1 ) {
			return 'risk';
		}
		return '';
	}

	/**
	 * Build the heading + body copy for a success-tier review notice.
	 *
	 * @since 1.3.2
	 * @param string $tier            'attack' | 'revenue' | 'risk'.
	 * @param float  $money_protected Protected revenue (store currency).
	 * @param int    $total_scored    Total scored customers.
	 * @param int    $high_risk_count High-risk customer count.
	 * @return array{0:string,1:string} Escaped [ heading_html, body_html ].
	 */
	private function success_notice_copy( string $tier, float $money_protected, int $total_scored, int $high_risk_count ): array {
		switch ( $tier ) {
			case 'attack':
				return array(
					esc_html__( 'TrustLens just blocked a card-testing attack', 'trustlens' ),
					esc_html__( 'It shut the attack down at checkout before it could rack up gateway fees and chargebacks. Enjoying TrustLens so far? A quick review helps other store owners find it.', 'trustlens' ),
				);
			case 'revenue':
				return array(
					sprintf(
						/* translators: %s: formatted amount of revenue protected. */
						esc_html__( 'TrustLens has protected %s for your store', 'trustlens' ),
						'<span class="wstl-review-amt">' . wp_kses_post( wc_price( $money_protected ) ) . '</span>'
					),
					esc_html__( "That's real money that stayed with you instead of walking out the door. Enjoying TrustLens so far? A quick review helps other store owners find it — and means a lot to a small team.", 'trustlens' ),
				);
			case 'risk':
			default:
				return array(
					sprintf(
						/* translators: %d: number of high-risk customers. */
						esc_html( _n( 'TrustLens flagged %d high-risk customer', 'TrustLens flagged %d high-risk customers', $high_risk_count, 'trustlens' ) ),
						$high_risk_count
					),
					sprintf(
						/* translators: 1: total customers scored, 2: number flagged high-risk. */
						esc_html__( 'It scored %1$d shoppers and flagged %2$d so you can step in before they cost you. Enjoying TrustLens so far? A quick review helps other store owners find it.', 'trustlens' ),
						$total_scored,
						$high_risk_count
					),
				);
		}
	}

	/**
	 * Render the shared review-request notice markup + dismissal script.
	 *
	 * The success tier and the time-based fallback render identical markup (same
	 * element IDs, nonce, and AJAX actions) and differ only in heading/body copy.
	 * Only one review notice ever renders per page load, so sharing the element
	 * IDs across tiers is safe.
	 *
	 * @since 1.3.2
	 * @param string $heading_html Escaped heading HTML.
	 * @param string $body_html    Escaped body HTML.
	 * @return void
	 */
	private function render_review_markup( string $heading_html, string $body_html ): void {
		$dismiss_nonce = wp_create_nonce( 'wstl_review_notice' );
		$review_url    = 'https://wordpress.org/support/plugin/trustlens/reviews/#new-post';
		?>
		<div class="notice notice-success is-dismissible wstl-review-notice" id="wstl-review-notice" data-nonce="<?php echo esc_attr( $dismiss_nonce ); ?>">
			<div class="wstl-review-row">
				<span class="wstl-review-icon" aria-hidden="true">
					<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M12 2.5 4.5 5.4v5.3c0 4.4 3 8.3 7.5 9.8 4.5-1.5 7.5-5.4 7.5-9.8V5.4L12 2.5Z" fill="#1E7A46" opacity=".14"/>
						<path d="M12 2.5 4.5 5.4v5.3c0 4.4 3 8.3 7.5 9.8 4.5-1.5 7.5-5.4 7.5-9.8V5.4L12 2.5Z" stroke="#1E7A46" stroke-width="1.6" stroke-linejoin="round"/>
						<path d="m8.6 11.7 2.3 2.3 4.5-4.6" stroke="#1E7A46" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>
					</svg>
				</span>
				<div class="wstl-review-main">
					<p class="wstl-review-head"><?php echo wp_kses_post( $heading_html ); ?></p>
					<p class="wstl-review-sub"><?php echo wp_kses_post( $body_html ); ?></p>
					<p class="wstl-review-cta">
						<a class="button button-primary wstl-review-btn" id="wstl-review-now" href="<?php echo esc_url( $review_url ); ?>" target="_blank" rel="noopener noreferrer"><span class="wstl-review-stars" aria-hidden="true">&#9733;&#9733;&#9733;&#9733;&#9733;</span> <?php esc_html_e( 'Leave a review', 'trustlens' ); ?></a>
						<button type="button" class="button-link wstl-review-later" id="wstl-review-remind-later"><?php esc_html_e( 'Remind me later', 'trustlens' ); ?></button>
						<button type="button" class="button-link wstl-review-dismiss" id="wstl-review-dismiss"><?php esc_html_e( "Don't show again", 'trustlens' ); ?></button>
					</p>
				</div>
			</div>
			<style>
			#wstl-review-notice.wstl-review-notice{border:1px solid #e0e0e0;border-left:4px solid #1E7A46;border-radius:8px;padding:0;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.08)}
			#wstl-review-notice .wstl-review-row{display:flex;gap:14px;padding:16px 40px 16px 18px}
			#wstl-review-notice .wstl-review-icon{flex:none;width:42px;height:42px;border-radius:50%;background:rgba(30,122,70,.12);display:flex;align-items:center;justify-content:center}
			#wstl-review-notice .wstl-review-icon svg{width:23px;height:23px;display:block}
			#wstl-review-notice .wstl-review-main{flex:1;min-width:0}
			#wstl-review-notice .wstl-review-head{margin:2px 0 0;font-size:15px;font-weight:700;color:#14283e;line-height:1.4}
			#wstl-review-notice .wstl-review-amt{color:#1E7A46;font-weight:800;font-variant-numeric:tabular-nums;white-space:nowrap}
			#wstl-review-notice .wstl-review-sub{margin:6px 0 0;font-size:13px;line-height:1.55;color:#5b6d80}
			#wstl-review-notice .wstl-review-cta{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:13px 0 2px}
			#wstl-review-notice .wstl-review-btn{display:inline-flex;align-items:center;gap:8px;background:#1E7A46;border-color:#1E7A46;color:#fff;box-shadow:0 1px 2px rgba(30,122,70,.25);text-shadow:none}
			#wstl-review-notice .wstl-review-btn:hover,#wstl-review-notice .wstl-review-btn:focus{background:#186a3c;border-color:#186a3c;color:#fff}
			#wstl-review-notice .wstl-review-stars{letter-spacing:1px;color:#E8A317;font-size:13px;line-height:1}
			#wstl-review-notice .wstl-review-later{color:#5b6d80;font-weight:600;text-decoration:none;padding:0 4px;cursor:pointer}
			#wstl-review-notice .wstl-review-later:hover{color:#14283e}
			#wstl-review-notice .wstl-review-dismiss{color:#9aa4b2;text-decoration:none;padding:0 4px;margin-left:auto;cursor:pointer}
			#wstl-review-notice .wstl-review-dismiss:hover{color:#5b6d80}
			@media screen and (max-width:600px){#wstl-review-notice .wstl-review-dismiss{margin-left:0}}
			</style>
		</div>
		<script>
		(function() {
			var notice = document.getElementById('wstl-review-notice');
			if (!notice) return;
			var nonce = notice.getAttribute('data-nonce');
			function postAction(action) {
				var body = new URLSearchParams();
				body.append('action', action);
				body.append('nonce', nonce);
				fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: body.toString() }).finally(function() { notice.style.display = 'none'; });
			}
			var reviewBtn = document.getElementById('wstl-review-now');
			if (reviewBtn) reviewBtn.addEventListener('click', function() { postAction('wstl_dismiss_review_notice'); });
			var remindBtn = document.getElementById('wstl-review-remind-later');
			if (remindBtn) remindBtn.addEventListener('click', function() { postAction('wstl_remind_later_review_notice'); });
			var dismissBtn = document.getElementById('wstl-review-dismiss');
			if (dismissBtn) dismissBtn.addEventListener('click', function() { postAction('wstl_dismiss_review_notice'); });
			notice.addEventListener('click', function(e) {
				if (e.target && e.target.classList && e.target.classList.contains('notice-dismiss')) {
					postAction('wstl_dismiss_review_notice');
				}
			});
		})();
		</script>
		<?php
	}

	/**
	 * Render the usage-data opt-in nudge for users who skipped the opt-in.
	 *
	 * @since 1.3.2
	 * @return bool True if the notice was rendered.
	 */
	private function maybe_render_optin_notice(): bool {
		if ( ! function_exists( 'wstl_fs' ) ) {
			return false;
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return false;
		}

		$fs          = wstl_fs();
		$sync_status = TrustLens_Historical_Sync::instance()->get_status();

		$should_show = self::should_show_optin_notice(
			$fs->is_anonymous(),
			$fs->is_registered(),
			current_user_can( 'manage_woocommerce' ),
			(bool) get_user_meta( $user_id, self::OPTIN_NOTICE_DISMISSED_META, true ),
			(int) get_user_meta( $user_id, self::OPTIN_NOTICE_REMIND_LATER_META, true ),
			(int) get_option( 'trustlens_installed_timestamp', 0 ),
			(int) ( $sync_status['total_customers'] ?? 0 ),
			time()
		);

		if ( ! $should_show ) {
			return false;
		}

		$dismiss_nonce = wp_create_nonce( 'wstl_optin_notice' );
		$reconnect_url = $fs->get_reconnect_url();
		?>
		<div class="notice notice-info is-dismissible" id="wstl-optin-notice" data-nonce="<?php echo esc_attr( $dismiss_nonce ); ?>">
			<p><strong><?php esc_html_e( 'Help improve TrustLens', 'trustlens' ); ?></strong></p>
			<p><?php esc_html_e( "Share your site's basic WordPress environment (like PHP and plugin versions) so we can catch compatibility issues early, fix problems faster, and keep improving TrustLens. We never collect your customers' data, orders, or payments.", 'trustlens' ); ?></p>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( $reconnect_url ); ?>"><?php esc_html_e( 'Share usage data', 'trustlens' ); ?></a>
				<button type="button" class="button" id="wstl-optin-remind-later"><?php esc_html_e( 'Remind me later', 'trustlens' ); ?></button>
				<button type="button" class="button button-link" id="wstl-optin-dismiss"><?php esc_html_e( "Don't show again", 'trustlens' ); ?></button>
			</p>
		</div>
		<script>
		(function() {
			var notice = document.getElementById('wstl-optin-notice');
			if (!notice) return;
			var nonce = notice.getAttribute('data-nonce');
			function postAction(action) {
				var body = new URLSearchParams();
				body.append('action', action);
				body.append('nonce', nonce);
				fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: body.toString() }).finally(function() { notice.style.display = 'none'; });
			}
			var remindBtn = document.getElementById('wstl-optin-remind-later');
			if (remindBtn) remindBtn.addEventListener('click', function() { postAction('wstl_remind_later_optin_notice'); });
			var dismissBtn = document.getElementById('wstl-optin-dismiss');
			if (dismissBtn) dismissBtn.addEventListener('click', function() { postAction('wstl_dismiss_optin_notice'); });
			notice.addEventListener('click', function(e) {
				if (e.target && e.target.classList && e.target.classList.contains('notice-dismiss')) {
					postAction('wstl_dismiss_optin_notice');
				}
			});
		})();
		</script>
		<?php
		return true;
	}

	/**
	 * Pure decision: should the usage-data opt-in nudge render?
	 *
	 * All WordPress/Freemius lookups are injected so this stays unit-testable.
	 *
	 * @since 1.3.2
	 * @param bool $is_anonymous  Freemius is_anonymous() — user skipped the opt-in.
	 * @param bool $is_registered Freemius is_registered() — user already opted in.
	 * @param bool $can_manage    current_user_can( 'manage_woocommerce' ).
	 * @param bool $dismissed     Whether the user permanently dismissed the nudge.
	 * @param int  $remind_until  Unix time until which the nudge is snoozed.
	 * @param int  $installed_at  Unix install timestamp.
	 * @param int  $customers     Tracked customer count.
	 * @param int  $now           Current Unix time.
	 * @return bool
	 */
	public static function should_show_optin_notice(
		bool $is_anonymous,
		bool $is_registered,
		bool $can_manage,
		bool $dismissed,
		int $remind_until,
		int $installed_at,
		int $customers,
		int $now
	): bool {
		if ( ! $can_manage ) {
			return false;
		}
		if ( ! $is_anonymous || $is_registered ) {
			return false;
		}
		if ( $dismissed ) {
			return false;
		}
		if ( $remind_until > $now ) {
			return false;
		}
		if ( $installed_at <= 0 ) {
			return false;
		}
		$days_installed = (int) floor( ( $now - $installed_at ) / DAY_IN_SECONDS );
		if ( $days_installed < self::OPTIN_NOTICE_MIN_DAYS_INSTALLED ) {
			return false;
		}
		if ( $customers < self::OPTIN_NOTICE_MIN_CUSTOMERS ) {
			return false;
		}
		return true;
	}

	public function ajax_dismiss_review_notice(): void {
		check_ajax_referer( 'wstl_review_notice', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'trustlens' ) ) );
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid user.', 'trustlens' ) ) );
		}

		update_user_meta( $user_id, self::REVIEW_NOTICE_DISMISSED_META, time() );
		delete_user_meta( $user_id, self::REVIEW_NOTICE_REMIND_LATER_META );
		wp_send_json_success( array( 'message' => __( 'Notice dismissed.', 'trustlens' ) ) );
	}

	public function ajax_remind_later_review_notice(): void {
		check_ajax_referer( 'wstl_review_notice', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'trustlens' ) ) );
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid user.', 'trustlens' ) ) );
		}

		update_user_meta( $user_id, self::REVIEW_NOTICE_REMIND_LATER_META, time() + ( 14 * DAY_IN_SECONDS ) );
		wp_send_json_success( array( 'message' => __( 'Reminder set.', 'trustlens' ) ) );
	}

	public function ajax_dismiss_optin_notice(): void {
		check_ajax_referer( 'wstl_optin_notice', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'trustlens' ) ) );
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid user.', 'trustlens' ) ) );
		}

		update_user_meta( $user_id, self::OPTIN_NOTICE_DISMISSED_META, time() );
		delete_user_meta( $user_id, self::OPTIN_NOTICE_REMIND_LATER_META );
		wp_send_json_success( array( 'message' => __( 'Notice dismissed.', 'trustlens' ) ) );
	}

	public function ajax_remind_later_optin_notice(): void {
		check_ajax_referer( 'wstl_optin_notice', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'trustlens' ) ) );
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid user.', 'trustlens' ) ) );
		}

		update_user_meta( $user_id, self::OPTIN_NOTICE_REMIND_LATER_META, time() + ( 14 * DAY_IN_SECONDS ) );
		wp_send_json_success( array( 'message' => __( 'Reminder set.', 'trustlens' ) ) );
	}
}
