<?php
/**
 * Review Prompt — Two-Step Sentiment Gate + Persistent Nudge
 *
 * Asks users if they're enjoying ClearPost after their 5th published post.
 * Happy users are routed to WordPress.org review page; unhappy users get
 * a feedback form that emails the founder.
 *
 * @package Simple_AI_Auto_Post
 * @since 2.5.0
 */

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

/**
 * WordPress.org review URL for this plugin.
 */
define( 'SAIAP_REVIEW_URL', 'https://wordpress.org/support/plugin/clearpost-simple-ai-auto-post/reviews/#new-post' );

/**
 * Minimum number of published ClearPost-generated posts before prompting.
 * The first publish is the peak success moment, so ask right away; the
 * sentiment-first modal routes unhappy users to private feedback instead
 * of WordPress.org.
 */
define( 'SAIAP_REVIEW_PROMPT_THRESHOLD', 1 );

/**
 * Get count of published ClearPost-generated posts.
 *
 * @return int
 */
function saiap_get_published_generated_count() {
	global $wpdb;
	return (int) $wpdb->get_var(
		"SELECT COUNT(*) FROM {$wpdb->posts} p
		 INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
		 WHERE p.post_type = 'post'
		   AND p.post_status = 'publish'
		   AND pm.meta_key = '_saiap_generated'
		   AND pm.meta_value = '1'"
	);
}

/**
 * Check whether the review modal should be shown.
 *
 * @return bool
 */
function saiap_should_show_review_modal() {
	$count = saiap_get_published_generated_count();
	if ( $count < SAIAP_REVIEW_PROMPT_THRESHOLD ) {
		return false;
	}

	$user_id = get_current_user_id();
	$status  = get_user_meta( $user_id, 'saiap_review_prompt_status', true );

	// Terminal states — never show modal again.
	if ( in_array( $status, array( 'clicked_review', 'dismissed_permanent', 'sent_feedback' ), true ) ) {
		return false;
	}

	// Temp dismissed — check if 30 days have passed for one re-show.
	if ( 'dismissed_temp' === $status ) {
		$dismissed_at = (int) get_user_meta( $user_id, 'saiap_review_prompt_dismissed_at', true );
		if ( ( time() - $dismissed_at ) < 30 * DAY_IN_SECONDS ) {
			return false;
		}
		// 30 days passed — show one more time, then it becomes permanent on next temp dismiss.
		$reshown = get_user_meta( $user_id, 'saiap_review_prompt_reshown', true );
		if ( $reshown ) {
			return false; // Already re-shown once after temp dismiss.
		}
		update_user_meta( $user_id, 'saiap_review_prompt_reshown', '1' );
		return true;
	}

	return true;
}

/**
 * Check whether the persistent nudge should be shown.
 *
 * @return bool
 */
function saiap_should_show_review_nudge() {
	$count = saiap_get_published_generated_count();
	if ( $count < SAIAP_REVIEW_PROMPT_THRESHOLD ) {
		return false;
	}

	$user_id = get_current_user_id();
	$status  = get_user_meta( $user_id, 'saiap_review_prompt_status', true );

	// Hide nudge only on terminal states.
	if ( in_array( $status, array( 'clicked_review', 'dismissed_permanent', 'sent_feedback' ), true ) ) {
		return false;
	}

	return true;
}

/**
 * Render the persistent review nudge line.
 */
function saiap_render_review_nudge() {
	if ( ! saiap_should_show_review_nudge() ) {
		return;
	}
	?>
	<p class="saiap-review-nudge">
		<?php
		printf(
			/* translators: %s: link to WordPress.org review page */
			esc_html__( 'Enjoying ClearPost? %s — it takes 30 seconds and helps us grow.', 'clearpost-simple-ai-auto-post' ),
			'<a href="' . esc_url( SAIAP_REVIEW_URL ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Leave a review on WordPress.org', 'clearpost-simple-ai-auto-post' ) . '</a>'
		);
		?>
	</p>
	<?php
}

/**
 * Render the two-step review modal.
 */
function saiap_render_review_modal() {
	if ( ! saiap_should_show_review_modal() ) {
		return;
	}

	$count = saiap_get_published_generated_count();
	?>
	<div id="saiap-review-modal" class="saiap-modal" style="display:none;">
		<div class="saiap-modal__backdrop"></div>
		<div class="saiap-modal__content saiap-review-modal__content">
			<button type="button" class="saiap-modal__close">&times;</button>

			<!-- Step 1: Sentiment Gate -->
			<div class="saiap-modal__body saiap-review-step" id="saiap-review-step-1">
				<h2><?php esc_html_e( 'Enjoying ClearPost?', 'clearpost-simple-ai-auto-post' ); ?></h2>
				<p>
					<?php
					if ( 1 === $count ) {
						esc_html_e( 'You just published your first post with ClearPost. How\'s it going?', 'clearpost-simple-ai-auto-post' );
					} else {
						printf(
							/* translators: %d: number of published posts */
							esc_html__( 'You\'ve published %d posts so far. How\'s it going?', 'clearpost-simple-ai-auto-post' ),
							(int) $count
						);
					}
					?>
				</p>
				<div class="saiap-review-modal__actions">
					<button type="button" class="button button-primary saiap-review-btn-positive">
						<?php esc_html_e( 'Yes, loving it!', 'clearpost-simple-ai-auto-post' ); ?>
					</button>
					<button type="button" class="button saiap-review-btn-negative">
						<?php esc_html_e( 'Not really', 'clearpost-simple-ai-auto-post' ); ?>
					</button>
				</div>
				<a href="#" class="saiap-review-dismiss-permanent"><?php esc_html_e( 'Don\'t ask again', 'clearpost-simple-ai-auto-post' ); ?></a>
			</div>

			<!-- Step 2a: Happy Path -->
			<div class="saiap-modal__body saiap-review-step" id="saiap-review-step-2a" style="display:none;">
				<h2><?php esc_html_e( 'That\'s great to hear!', 'clearpost-simple-ai-auto-post' ); ?></h2>
				<p><?php esc_html_e( 'Would you mind leaving a quick review on WordPress.org? Even one sentence helps us reach more people like you.', 'clearpost-simple-ai-auto-post' ); ?></p>
				<div class="saiap-review-modal__actions">
					<a href="<?php echo esc_url( SAIAP_REVIEW_URL ); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary saiap-review-btn-leave-review">
						<?php esc_html_e( 'Leave a Review', 'clearpost-simple-ai-auto-post' ); ?>
					</a>
					<a href="#" class="saiap-review-dismiss-temp"><?php esc_html_e( 'Maybe later', 'clearpost-simple-ai-auto-post' ); ?></a>
				</div>
			</div>

			<!-- Step 2b: Unhappy Path -->
			<div class="saiap-modal__body saiap-review-step" id="saiap-review-step-2b" style="display:none;">
				<h2><?php esc_html_e( 'Sorry to hear that', 'clearpost-simple-ai-auto-post' ); ?></h2>
				<p><?php esc_html_e( 'What could we do better? We read every message.', 'clearpost-simple-ai-auto-post' ); ?></p>
				<textarea id="saiap-review-feedback-text" rows="4" placeholder="<?php esc_attr_e( 'Your feedback...', 'clearpost-simple-ai-auto-post' ); ?>"></textarea>
				<div class="saiap-review-modal__actions">
					<button type="button" class="button button-primary saiap-review-btn-send-feedback">
						<?php esc_html_e( 'Send Feedback', 'clearpost-simple-ai-auto-post' ); ?>
					</button>
				</div>
			</div>

			<!-- Step 2b Thank You -->
			<div class="saiap-modal__body saiap-review-step" id="saiap-review-step-thanks" style="display:none;">
				<h2><?php esc_html_e( 'Thanks for the feedback!', 'clearpost-simple-ai-auto-post' ); ?></h2>
				<p><?php esc_html_e( 'We appreciate you taking the time. We\'ll use this to make ClearPost better.', 'clearpost-simple-ai-auto-post' ); ?></p>
				<div class="saiap-review-modal__actions">
					<button type="button" class="button saiap-review-btn-close"><?php esc_html_e( 'Close', 'clearpost-simple-ai-auto-post' ); ?></button>
				</div>
			</div>
		</div>
	</div>
	<?php
}

/**
 * AJAX: Dismiss review prompt (temp or permanent).
 */
function saiap_ajax_review_prompt_dismiss() {
	check_ajax_referer( 'saiap_review_prompt_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	$type    = isset( $_POST['dismiss_type'] ) ? sanitize_text_field( wp_unslash( $_POST['dismiss_type'] ) ) : '';
	$user_id = get_current_user_id();

	if ( 'permanent' === $type ) {
		update_user_meta( $user_id, 'saiap_review_prompt_status', 'dismissed_permanent' );
	} elseif ( 'temp' === $type ) {
		update_user_meta( $user_id, 'saiap_review_prompt_status', 'dismissed_temp' );
		update_user_meta( $user_id, 'saiap_review_prompt_dismissed_at', time() );
	}

	wp_send_json_success();
}
add_action( 'wp_ajax_saiap_review_prompt_dismiss', 'saiap_ajax_review_prompt_dismiss' );

/**
 * AJAX: Track review link click.
 */
function saiap_ajax_review_prompt_clicked() {
	check_ajax_referer( 'saiap_review_prompt_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	$user_id = get_current_user_id();
	update_user_meta( $user_id, 'saiap_review_prompt_status', 'clicked_review' );
	update_user_meta( $user_id, 'saiap_review_prompt_sentiment', 'positive' );

	wp_send_json_success();
}
add_action( 'wp_ajax_saiap_review_prompt_clicked', 'saiap_ajax_review_prompt_clicked' );

/**
 * AJAX: Track sentiment (positive/negative).
 */
function saiap_ajax_review_prompt_sentiment() {
	check_ajax_referer( 'saiap_review_prompt_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	$sentiment = isset( $_POST['sentiment'] ) ? sanitize_text_field( wp_unslash( $_POST['sentiment'] ) ) : '';
	if ( ! in_array( $sentiment, array( 'positive', 'negative' ), true ) ) {
		wp_send_json_error( 'Invalid sentiment' );
	}

	update_user_meta( get_current_user_id(), 'saiap_review_prompt_sentiment', $sentiment );

	wp_send_json_success();
}
add_action( 'wp_ajax_saiap_review_prompt_sentiment', 'saiap_ajax_review_prompt_sentiment' );

/**
 * AJAX: Submit feedback and email it to the founder.
 */
function saiap_ajax_review_prompt_feedback() {
	check_ajax_referer( 'saiap_review_prompt_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	$feedback = isset( $_POST['feedback'] ) ? sanitize_textarea_field( wp_unslash( $_POST['feedback'] ) ) : '';
	if ( empty( $feedback ) ) {
		wp_send_json_error( 'Empty feedback' );
	}

	$user_id = get_current_user_id();
	update_user_meta( $user_id, 'saiap_review_prompt_status', 'sent_feedback' );
	update_user_meta( $user_id, 'saiap_review_prompt_sentiment', 'negative' );

	// Send feedback via the public feedback endpoint (no API key needed).
	$domain    = saiap_get_server_host();
	$site_name = get_bloginfo( 'name' );
	$user      = wp_get_current_user();

	wp_remote_post(
		SAIAP_PREMIUM_API_URL . '/api/feedback',
		array(
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode(
				array(
					'domain'     => $domain,
					'site_name'  => $site_name,
					'user_name'  => $user->display_name,
					'user_email' => $user->user_email,
					'feedback'   => $feedback,
				)
			),
			'timeout' => 15,
		)
	);

	wp_send_json_success();
}
add_action( 'wp_ajax_saiap_review_prompt_feedback', 'saiap_ajax_review_prompt_feedback' );

/**
 * Set review prompt ready flag when the Nth post is published.
 *
 * Hooks into the existing transition_post_status to detect when a
 * ClearPost-generated draft is manually published by the user.
 *
 * @param string  $new_status New post status.
 * @param string  $old_status Old post status.
 * @param WP_Post $post       Post object.
 */
function saiap_maybe_set_review_prompt_ready( $new_status, $old_status, $post ) {
	if ( 'publish' !== $new_status || 'draft' !== $old_status ) {
		return;
	}

	$is_generated = get_post_meta( $post->ID, '_saiap_generated', true );
	if ( ! $is_generated ) {
		return;
	}

	$user_id = get_current_user_id();
	$status  = get_user_meta( $user_id, 'saiap_review_prompt_status', true );

	// Don't overwrite terminal states.
	if ( in_array( $status, array( 'clicked_review', 'dismissed_permanent', 'sent_feedback' ), true ) ) {
		return;
	}

	$count = saiap_get_published_generated_count();
	if ( $count >= SAIAP_REVIEW_PROMPT_THRESHOLD ) {
		update_user_meta( $user_id, 'saiap_review_prompt_ready', '1' );
	}
}
add_action( 'transition_post_status', 'saiap_maybe_set_review_prompt_ready', 20, 3 );

/**
 * Check whether the admin-wide review notice should be shown.
 *
 * @return bool
 */
function saiap_should_show_review_notice() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return false;
	}

	$user_id = get_current_user_id();
	$status  = get_user_meta( $user_id, 'saiap_review_prompt_status', true );

	// Terminal states — never show again.
	if ( in_array( $status, array( 'clicked_review', 'dismissed_permanent', 'sent_feedback' ), true ) ) {
		return false;
	}

	// Snoozed — wait 30 days before showing again.
	if ( 'dismissed_temp' === $status ) {
		$dismissed_at = (int) get_user_meta( $user_id, 'saiap_review_prompt_dismissed_at', true );
		if ( ( time() - $dismissed_at ) < 30 * DAY_IN_SECONDS ) {
			return false;
		}
	}

	return saiap_get_published_generated_count() >= SAIAP_REVIEW_PROMPT_THRESHOLD;
}

/**
 * Build a nonce-protected action URL for the review notice.
 *
 * @param string $action Action slug: review|later|never.
 * @return string
 */
function saiap_review_notice_action_url( $action ) {
	return wp_nonce_url(
		add_query_arg( 'saiap_review_action', $action, admin_url() ),
		'saiap_review_notice'
	);
}

/**
 * Render the admin-wide review notice.
 *
 * The two-step modal only renders on the ClearPost dashboard page, which
 * users with scheduled generation rarely revisit. This notice covers the
 * rest of wp-admin so the review ask is actually seen.
 */
function saiap_render_review_notice() {
	$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
	if ( $screen && 'toplevel_page_saiap' === $screen->id ) {
		return; // The dashboard page has the modal + nudge.
	}

	if ( ! saiap_should_show_review_notice() ) {
		return;
	}

	$count = saiap_get_published_generated_count();
	// Per the v2.0.53 changelog: celebrates milestones at 5, 10, 25, 50+.
	// $milestone is the value to celebrate, or null when $count isn't on a milestone.
	$milestone_targets = array( 5, 10, 25, 50 );
	$milestone         = in_array( $count, $milestone_targets, true ) ? $count : null;
	?>
	<div class="notice notice-info saiap-review-notice">
		<p>
			<strong><?php esc_html_e( 'Enjoying ClearPost?', 'clearpost-simple-ai-auto-post' ); ?></strong>
			<?php
			if ( 1 === $count ) {
				esc_html_e( 'You just published your first post with ClearPost. A quick review on WordPress.org takes 30 seconds and helps us reach more people like you.', 'clearpost-simple-ai-auto-post' );
			} elseif ( null !== $milestone && $count === $milestone ) {
				printf(
					/* translators: %d: milestone number of published posts */
					esc_html__( 'You just hit %d published posts with it. A quick review on WordPress.org takes 30 seconds and helps us reach more people like you.', 'clearpost-simple-ai-auto-post' ),
					(int) $milestone
				);
			} else {
				printf(
					/* translators: %d: number of published posts */
					esc_html__( 'You\'ve published %d posts with it. A quick review on WordPress.org takes 30 seconds and helps us reach more people like you.', 'clearpost-simple-ai-auto-post' ),
					(int) $count
				);
			}
			?>
		</p>
		<p>
			<a href="<?php echo esc_url( saiap_review_notice_action_url( 'review' ) ); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary">
				<?php esc_html_e( 'Leave a Review', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<a href="<?php echo esc_url( saiap_review_notice_action_url( 'later' ) ); ?>" class="button" style="margin-left:6px;">
				<?php esc_html_e( 'Maybe later', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<a href="<?php echo esc_url( saiap_review_notice_action_url( 'never' ) ); ?>" style="margin-left:10px;">
				<?php esc_html_e( 'Don\'t ask again', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
		</p>
	</div>
	<?php
}
add_action( 'admin_notices', 'saiap_render_review_notice' );

/**
 * Handle review notice action links (no JS required).
 */
function saiap_handle_review_notice_action() {
	if ( ! isset( $_GET['saiap_review_action'] ) ) {
		return;
	}

	check_admin_referer( 'saiap_review_notice' );

	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$action  = sanitize_text_field( wp_unslash( $_GET['saiap_review_action'] ) );
	$user_id = get_current_user_id();

	if ( 'review' === $action ) {
		update_user_meta( $user_id, 'saiap_review_prompt_status', 'clicked_review' );
		update_user_meta( $user_id, 'saiap_review_prompt_sentiment', 'positive' );
		wp_redirect( SAIAP_REVIEW_URL ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- intentional external redirect to WordPress.org.
		exit;
	}

	if ( 'never' === $action ) {
		update_user_meta( $user_id, 'saiap_review_prompt_status', 'dismissed_permanent' );
	} elseif ( 'later' === $action ) {
		update_user_meta( $user_id, 'saiap_review_prompt_status', 'dismissed_temp' );
		update_user_meta( $user_id, 'saiap_review_prompt_dismissed_at', time() );
	}

	$referer = wp_get_referer();
	wp_safe_redirect( $referer ? $referer : admin_url() );
	exit;
}
add_action( 'admin_init', 'saiap_handle_review_notice_action' );
