<?php
declare(strict_types=1);

namespace Wohno\Plugin\Admin;

use Wohno\Plugin\Security\Secret;

use const Wohno\Plugin\VERSION;

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

/**
 * Light-touch growth helpers, free of any phone-home/telemetry:
 *
 * - A time-delayed, dismissible "leave a review" notice for engaged users.
 * - A deactivation feedback modal on the Plugins page. The reason is sent only
 *   if the user chooses to — via a pre-filled e-mail (mailto) they control; the
 *   plugin never silently collects or transmits anything.
 */
final class Feedback {

	private const OPTION_INSTALLED  = 'wohno_installed_at';
	private const OPTION_REVIEW     = 'wohno_review_dismissed';
	private const REVIEW_DELAY_DAYS = 14;

	private const REVIEW_URL  = 'https://wordpress.org/support/plugin/wohno/reviews/';
	private const FEEDBACK_TO = 'info@wohno.de';

	/**
	 * Register admin hooks.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_init', array( $this, 'ensure_install_time' ) );
		add_action( 'admin_init', array( $this, 'maybe_handle_review_action' ) );
		add_action( 'admin_notices', array( $this, 'maybe_review_prompt' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_deactivation' ) );
		add_action( 'admin_footer-plugins.php', array( $this, 'render_deactivation_modal' ) );
	}

	/**
	 * Record the first-seen timestamp (lazy; no activation hook needed).
	 *
	 * @return void
	 */
	public function ensure_install_time(): void {
		if ( ! get_option( self::OPTION_INSTALLED ) ) {
			update_option( self::OPTION_INSTALLED, time(), false );
		}
	}

	/**
	 * Handle the review-notice actions (dismiss / snooze) via a nonce'd link.
	 *
	 * @return void
	 */
	public function maybe_handle_review_action(): void {
		if ( ! isset( $_GET['wohno_review'] ) || ! current_user_can( 'manage_options' ) ) {
			return;
		}
		check_admin_referer( 'wohno_review' );

		$action = sanitize_key( wp_unslash( (string) $_GET['wohno_review'] ) );
		if ( 'snooze' === $action ) {
			update_option( self::OPTION_INSTALLED, time(), false ); // Ask again after the delay.
		} else {
			update_option( self::OPTION_REVIEW, '1', false ); // Dismiss for good.
		}

		wp_safe_redirect( remove_query_arg( array( 'wohno_review', '_wpnonce' ) ) );
		exit;
	}

	/**
	 * Show a dismissible review prompt to engaged admins after a delay.
	 *
	 * @return void
	 */
	public function maybe_review_prompt(): void {
		if ( ! current_user_can( 'manage_options' ) || '1' === get_option( self::OPTION_REVIEW ) ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		$id     = $screen ? (string) $screen->id : '';
		if ( 'plugins' !== $id && ! str_contains( $id, 'wohno-settings' ) ) {
			return; // Only on the Plugins list + our settings page.
		}

		// Only engaged installs: a key must be configured.
		if ( '' === Secret::decrypt( (string) get_option( 'wohno_api_key', '' ) ) ) {
			return;
		}

		$installed = (int) get_option( self::OPTION_INSTALLED, time() );
		if ( ( time() - $installed ) < self::REVIEW_DELAY_DAYS * DAY_IN_SECONDS ) {
			return;
		}

		$dismiss = wp_nonce_url( add_query_arg( 'wohno_review', 'dismiss' ), 'wohno_review' );
		$snooze  = wp_nonce_url( add_query_arg( 'wohno_review', 'snooze' ), 'wohno_review' );
		?>
		<div class="notice notice-info">
			<p>
				<strong><?php echo esc_html__( 'Gefällt dir das Wohno-Plugin?', 'wohno' ); ?></strong>
				<?php echo ' ' . esc_html__( 'Eine kurze Bewertung auf wordpress.org hilft uns sehr und anderen Maklern bei der Auswahl.', 'wohno' ); ?>
			</p>
			<p>
				<a href="<?php echo esc_url( self::REVIEW_URL ); ?>" class="button button-primary" target="_blank" rel="noopener">
					<?php echo esc_html__( 'Jetzt bewerten', 'wohno' ); ?>
				</a>
				<a href="<?php echo esc_url( $dismiss ); ?>" class="button"><?php echo esc_html__( 'Bereits erledigt', 'wohno' ); ?></a>
				<a href="<?php echo esc_url( $snooze ); ?>" class="button-link"><?php echo esc_html__( 'Später erinnern', 'wohno' ); ?></a>
			</p>
		</div>
		<?php
	}

	/**
	 * Enqueue the deactivation-feedback modal script on the Plugins page only.
	 *
	 * @param string $hook Current admin page hook suffix.
	 * @return void
	 */
	public function enqueue_deactivation( string $hook ): void {
		if ( 'plugins.php' !== $hook ) {
			return;
		}
		wp_enqueue_style(
			'wohno-admin-feedback',
			WOHNO_PLUGIN_URL . 'assets/css/admin-feedback.css',
			array(),
			VERSION
		);
		wp_enqueue_script(
			'wohno-admin-feedback',
			WOHNO_PLUGIN_URL . 'assets/js/admin-feedback.js',
			array(),
			VERSION,
			true
		);
		wp_localize_script(
			'wohno-admin-feedback',
			'wohnoFeedback',
			array(
				'plugin'  => plugin_basename( WOHNO_PLUGIN_FILE ),
				'mailto'  => self::FEEDBACK_TO,
				'subject' => __( 'Wohno-Plugin – Feedback zur Deaktivierung', 'wohno' ),
				'site'    => home_url( '/' ),
			)
		);
	}

	/**
	 * Render the (hidden) deactivation-feedback modal markup.
	 *
	 * Styles are enqueued separately ({@see self::enqueue_deactivation()}).
	 *
	 * @return void
	 */
	public function render_deactivation_modal(): void {
		$reasons = array(
			'temporary' => __( 'Nur vorübergehend / Fehlersuche', 'wohno' ),
			'better'    => __( 'Ich habe ein besseres Plugin gefunden', 'wohno' ),
			'broken'    => __( 'Funktioniert nicht wie erwartet', 'wohno' ),
			'missing'   => __( 'Mir fehlt eine Funktion', 'wohno' ),
			'other'     => __( 'Sonstiges', 'wohno' ),
		);
		?>
		<div class="wohno-fb-overlay" data-wohno-fb>
			<div class="wohno-fb" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr__( 'Feedback zur Deaktivierung', 'wohno' ); ?>">
				<h2><?php echo esc_html__( 'Schade, dass du gehst!', 'wohno' ); ?></h2>
				<p class="desc"><?php echo esc_html__( 'Magst du uns kurz sagen, warum? Das hilft uns, das Plugin zu verbessern. (Optional)', 'wohno' ); ?></p>
				<div class="wohno-fb__reasons">
					<?php $first = true; ?>
					<?php foreach ( $reasons as $value => $label ) : ?>
						<label>
							<input type="radio" name="wohno_fb_reason" value="<?php echo esc_attr( $value ); ?>" <?php checked( $first ); ?> />
							<span><?php echo esc_html( $label ); ?></span>
						</label>
						<?php $first = false; ?>
					<?php endforeach; ?>
				</div>
				<textarea data-wohno-fb-message placeholder="<?php echo esc_attr__( 'Optional: Was hat gefehlt oder nicht funktioniert?', 'wohno' ); ?>"></textarea>
				<div class="wohno-fb__actions">
					<button type="button" class="button button-primary" data-wohno-fb-send><?php echo esc_html__( 'Feedback senden & deaktivieren', 'wohno' ); ?></button>
					<a href="#" class="button wohno-fb__skip" data-wohno-fb-skip><?php echo esc_html__( 'Überspringen & deaktivieren', 'wohno' ); ?></a>
				</div>
			</div>
		</div>
		<?php
	}
}
