<?php
/**
 * Review CTA helpers for Vareon Calculator Suite Lite.
 *
 * @package Vareon_Calculator_Suite_Lite
 */

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

/**
 * Get the option name used to store review CTA state.
 *
 * @return string
 */
function vareoncalc_get_review_cta_option_name() {
	return 'vareoncalc_review_cta_state';
}

/**
 * Get the default review CTA state.
 *
 * @return array
 */
function vareoncalc_get_review_cta_default_state() {
	return array(
		'qualified_settings_visits' => 0,
		'first_prompt_seen_at'      => 0,
		'last_prompt_seen_at'       => 0,
		'next_prompt_at'            => 0,
		'maybe_later_count'         => 0,
		'review_clicked_at'         => 0,
		'help_clicked_at'           => 0,
	);
}

/**
 * Return the current review CTA state.
 *
 * @return array
 */
function vareoncalc_get_review_cta_state() {
	$state    = get_option( vareoncalc_get_review_cta_option_name(), array() );
	$defaults = vareoncalc_get_review_cta_default_state();

	if ( ! is_array( $state ) ) {
		$state = array();
	}

	foreach ( $defaults as $key => $default_value ) {
		$state[ $key ] = isset( $state[ $key ] ) ? absint( $state[ $key ] ) : $default_value;
	}

	return $state;
}

/**
 * Persist the review CTA state.
 *
 * @param array $state State to save.
 * @return void
 */
function vareoncalc_set_review_cta_state( array $state ) {
	$defaults = vareoncalc_get_review_cta_default_state();
	$clean    = array();

	foreach ( $defaults as $key => $default_value ) {
		$clean[ $key ] = isset( $state[ $key ] ) ? absint( $state[ $key ] ) : $default_value;
	}

	$option_name = vareoncalc_get_review_cta_option_name();
	$existing    = get_option( $option_name, null );

	if ( null === $existing ) {
		add_option( $option_name, $clean, '', 'no' );
		return;
	}

	update_option( $option_name, $clean );
}

/**
 * Get the current GMT timestamp for CTA scheduling.
 *
 * @return int
 */
function vareoncalc_get_review_cta_now() {
	return time();
}

/**
 * Get the WordPress.org review URL for Lite.
 *
 * @return string
 */
function vareoncalc_get_review_cta_review_url() {
	return 'https://wordpress.org/support/plugin/vareon-calculator-suite-lite/reviews/#new-post';
}

/**
 * Get the support URL for Lite.
 *
 * @return string
 */
function vareoncalc_get_review_cta_support_url() {
	return 'https://wordpress.org/support/plugin/vareon-calculator-suite-lite/';
}

/**
 * Get the default settings page URL used by CTA actions.
 *
 * @return string
 */
function vareoncalc_get_review_cta_settings_url() {
	return add_query_arg(
		array(
			'page' => 'vareoncalc',
			'tab'  => 'general',
		),
		admin_url( 'options-general.php' )
	);
}

/**
 * Get the snooze duration in seconds for a Maybe Later click count.
 *
 * @param int $maybe_later_count Number of Maybe Later clicks.
 * @return int
 */
function vareoncalc_get_review_cta_snooze_seconds( $maybe_later_count ) {
	return $maybe_later_count >= 3 ? 30 * DAY_IN_SECONDS : 14 * DAY_IN_SECONDS;
}

/**
 * Track one qualified settings-page visit.
 *
 * @param string $active_tab Active tab slug.
 * @return void
 */
function vareoncalc_track_review_cta_settings_visit( $active_tab ) {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	if ( 'welcome' === $active_tab ) {
		return;
	}

	$state                               = vareoncalc_get_review_cta_state();
	$state['qualified_settings_visits'] += 1;
	vareoncalc_set_review_cta_state( $state );
}

/**
 * Determine whether the main review CTA should render.
 *
 * @return bool
 */
function vareoncalc_should_render_main_review_cta() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return false;
	}

	$state = vareoncalc_get_review_cta_state();
	if ( ! empty( $state['review_clicked_at'] ) ) {
		return false;
	}

	if ( $state['qualified_settings_visits'] < 3 ) {
		return false;
	}

	$now = vareoncalc_get_review_cta_now();
	if ( ! empty( $state['next_prompt_at'] ) && $state['next_prompt_at'] > $now ) {
		return false;
	}

	return true;
}

/**
 * Build an admin-post action URL for a review CTA intent.
 *
 * @param string $intent  Action intent.
 * @param string $context CTA context.
 * @return string
 */
function vareoncalc_get_review_cta_action_url( $intent, $context = '' ) {
	$args = array(
		'action' => 'vareoncalc_review_cta',
		'intent' => sanitize_key( $intent ),
	);

	if ( '' !== $context ) {
		$args['context'] = sanitize_key( $context );
	}

	$url = add_query_arg( $args, admin_url( 'admin-post.php' ) );

	return wp_nonce_url( $url, 'vareoncalc_review_cta' );
}

/**
 * Get common action URLs for review CTA surfaces.
 *
 * @param string $context CTA context.
 * @return array
 */
function vareoncalc_get_review_cta_action_urls( $context ) {
	return array(
		'review' => vareoncalc_get_review_cta_action_url( 'review', $context ),
		'later'  => vareoncalc_get_review_cta_action_url( 'later', $context ),
		'help'   => vareoncalc_get_review_cta_action_url( 'help', $context ),
	);
}

/**
 * Render the main settings-page review CTA and advance its cadence.
 *
 * @return string
 */
function vareoncalc_render_main_review_cta() {
	if ( ! vareoncalc_should_render_main_review_cta() ) {
		return '';
	}

	$state                        = vareoncalc_get_review_cta_state();
	$now                          = vareoncalc_get_review_cta_now();
	$state['last_prompt_seen_at'] = $now;

	if ( empty( $state['first_prompt_seen_at'] ) ) {
		$state['first_prompt_seen_at'] = $now;
		$state['next_prompt_at']       = $now + ( 7 * DAY_IN_SECONDS );
	} elseif ( $state['maybe_later_count'] > 0 ) {
		$state['next_prompt_at'] = $now + vareoncalc_get_review_cta_snooze_seconds( $state['maybe_later_count'] );
	} else {
		$state['next_prompt_at'] = $now + ( 30 * DAY_IN_SECONDS );
	}

	vareoncalc_set_review_cta_state( $state );

	$urls = vareoncalc_get_review_cta_action_urls( 'main' );

	ob_start();
	?>
	<div class="vareoncalc-review-cta" role="region" aria-labelledby="vareoncalc-review-cta-title">
		<div class="vareoncalc-review-cta__media" aria-hidden="true">
			<div class="vareoncalc-review-cta__badge">
				<span class="dashicons dashicons-star-filled"></span>
			</div>
		</div>
		<div class="vareoncalc-review-cta__content">
			<div class="vareoncalc-review-cta__stars" aria-hidden="true">
				<span class="dashicons dashicons-star-filled"></span>
				<span class="dashicons dashicons-star-filled"></span>
				<span class="dashicons dashicons-star-filled"></span>
				<span class="dashicons dashicons-star-filled"></span>
				<span class="dashicons dashicons-star-filled"></span>
			</div>
			<h3 id="vareoncalc-review-cta-title" class="vareoncalc-review-cta__title"><?php esc_html_e( 'Enjoying Vareon Calculator Suite Lite?', 'vareon-calculator-suite-lite' ); ?></h3>
			<p class="vareoncalc-review-cta__text"><?php esc_html_e( 'If it has been useful on your site, a quick review on WordPress.org helps other users find it.', 'vareon-calculator-suite-lite' ); ?></p>
			<div class="vareoncalc-review-cta__actions">
				<a href="<?php echo esc_url( $urls['review'] ); ?>" class="button button-primary vareoncalc-review-cta__button vareoncalc-review-cta__button--primary"><?php esc_html_e( 'Leave a Review', 'vareon-calculator-suite-lite' ); ?></a>
				<a href="<?php echo esc_url( $urls['later'] ); ?>" class="button vareoncalc-review-cta__button"><?php esc_html_e( 'Maybe Later', 'vareon-calculator-suite-lite' ); ?></a>
				<a href="<?php echo esc_url( $urls['help'] ); ?>" class="vareoncalc-review-cta__help-link"><?php esc_html_e( 'Need Help Instead?', 'vareon-calculator-suite-lite' ); ?></a>
			</div>
		</div>
	</div>
	<?php

	return ob_get_clean();
}

/**
 * Render the quiet footer review/help card.
 *
 * @return string
 */
function vareoncalc_render_footer_review_cta() {
	$urls = vareoncalc_get_review_cta_action_urls( 'footer' );

	ob_start();
	?>
	<div class="vareoncalc-review-quiet-card" role="complementary" aria-labelledby="vareoncalc-review-footer-title">
		<div class="vareoncalc-review-quiet-card__body">
			<div class="vareoncalc-review-quiet-card__eyebrow"><?php esc_html_e( 'Review or Support', 'vareon-calculator-suite-lite' ); ?></div>
			<h3 id="vareoncalc-review-footer-title" class="vareoncalc-review-quiet-card__title"><?php esc_html_e( 'Helpful on your site?', 'vareon-calculator-suite-lite' ); ?></h3>
			<p class="vareoncalc-review-quiet-card__text"><?php esc_html_e( 'Leave a quick review or contact support.', 'vareon-calculator-suite-lite' ); ?></p>
		</div>
		<div class="vareoncalc-review-quiet-card__actions">
			<a href="<?php echo esc_url( $urls['review'] ); ?>" class="button button-primary vareoncalc-review-quiet-card__button"><?php esc_html_e( 'Leave a Review', 'vareon-calculator-suite-lite' ); ?></a>
			<a href="<?php echo esc_url( $urls['help'] ); ?>" class="button vareoncalc-review-quiet-card__button"><?php esc_html_e( 'Contact Support', 'vareon-calculator-suite-lite' ); ?></a>
		</div>
	</div>
	<?php

	return ob_get_clean();
}

/**
 * Render the small docs-page review micro CTA.
 *
 * @return string
 */
function vareoncalc_render_docs_review_micro_cta() {
	$urls = vareoncalc_get_review_cta_action_urls( 'docs' );

	ob_start();
	?>
	<div class="vareoncalc-review-micro-cta" role="complementary" aria-labelledby="vareoncalc-review-docs-title">
		<div class="vareoncalc-review-micro-cta__copy">
			<h4 id="vareoncalc-review-docs-title" class="vareoncalc-review-micro-cta__title"><?php esc_html_e( 'Enjoying Lite? A quick review helps.', 'vareon-calculator-suite-lite' ); ?></h4>
		</div>
		<div class="vareoncalc-review-micro-cta__actions">
			<a href="<?php echo esc_url( $urls['review'] ); ?>" class="button button-primary vareoncalc-review-micro-cta__button"><?php esc_html_e( 'Leave a Review', 'vareon-calculator-suite-lite' ); ?></a>
			<a href="<?php echo esc_url( $urls['help'] ); ?>" class="button vareoncalc-review-micro-cta__button"><?php esc_html_e( 'Contact Support', 'vareon-calculator-suite-lite' ); ?></a>
		</div>
	</div>
	<?php

	return ob_get_clean();
}

/**
 * Handle review CTA action clicks.
 *
 * @return void
 */
function vareoncalc_handle_review_cta_action() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die(
			esc_html__( 'You do not have permission to perform this action.', 'vareon-calculator-suite-lite' ),
			esc_html__( 'Error', 'vareon-calculator-suite-lite' ),
			array( 'response' => 403 )
		);
	}

	check_admin_referer( 'vareoncalc_review_cta' );

	$intent = isset( $_GET['intent'] ) ? sanitize_key( wp_unslash( $_GET['intent'] ) ) : '';
	$state  = vareoncalc_get_review_cta_state();
	$now    = vareoncalc_get_review_cta_now();

	switch ( $intent ) {
		case 'review':
			$state['review_clicked_at']   = $now;
			$state['next_prompt_at']      = 0;
			$state['last_prompt_seen_at'] = $now;
			vareoncalc_set_review_cta_state( $state );
			// phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Redirect target is a hardcoded trusted WordPress.org review URL.
			wp_redirect( esc_url_raw( vareoncalc_get_review_cta_review_url() ) );
			exit;

		case 'help':
			$state['help_clicked_at']     = $now;
			$state['next_prompt_at']      = $now + ( 30 * DAY_IN_SECONDS );
			$state['last_prompt_seen_at'] = $now;
			vareoncalc_set_review_cta_state( $state );
			// phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Redirect target is a hardcoded trusted support URL.
			wp_redirect( esc_url_raw( vareoncalc_get_review_cta_support_url() ) );
			exit;

		case 'later':
			$state['maybe_later_count']  += 1;
			$state['next_prompt_at']      = $now + vareoncalc_get_review_cta_snooze_seconds( $state['maybe_later_count'] );
			$state['last_prompt_seen_at'] = $now;
			vareoncalc_set_review_cta_state( $state );
			wp_safe_redirect( esc_url_raw( vareoncalc_get_review_cta_settings_url() ) );
			exit;
	}

	wp_safe_redirect( esc_url_raw( vareoncalc_get_review_cta_settings_url() ) );
	exit;
}
add_action( 'admin_post_vareoncalc_review_cta', 'vareoncalc_handle_review_cta_action' );
