<?php
/**
 * Uninstall Handler
 *
 * Handles plugin uninstallation with user confirmation dialog.
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

/**
 * UninstallHandler Class
 */
class UninstallHandler {
	
	/**
	 * Initialize uninstall handler
	 */
	public static function init(): void {
		add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueueScripts' ] );

		// Add JavaScript to intercept delete actions (must be in footer for plugins page)
		add_action( 'admin_footer', [ __CLASS__, 'showUninstallNotice' ], 999 );

		// Capture feedback on the deactivate request itself (before the plugin shuts down).
		add_action( 'admin_init', [ __CLASS__, 'captureDeactivationFeedbackFromRequest' ], 1 );
	}

	/**
	 * Register AJAX handlers for uninstall/deactivation flows.
	 */
	public static function registerAjaxHandlers(): void {
		static $registered = false;
		if ( $registered ) {
			return;
		}

		$registered = true;
		add_action( 'wp_ajax_wpps_set_delete_preference', [ __CLASS__, 'handleSetDeletePreference' ] );
		add_action( 'wp_ajax_wpps_deactivation_feedback', [ __CLASS__, 'handleDeactivationFeedback' ] );
	}

	/**
	 * Enqueue scripts for uninstall handler
	 *
	 * @return void
	 */
	public static function enqueueScripts(): void {
		$screen = get_current_screen();
		if ( ! $screen || $screen->id !== 'plugins' ) {
			return;
		}
		
		wp_enqueue_script( 'jquery' );
	}
	
	/**
	 * Show uninstall modal (with wipe-data checkbox) on plugins page
	 */
	public static function showUninstallNotice(): void {
		$screen = get_current_screen();
		if ( ! $screen || $screen->id !== 'plugins' ) {
			return;
		}

		$plugin_file = defined( 'WP_POWERSUITE_PLUGIN_BASENAME' )
			? WP_POWERSUITE_PLUGIN_BASENAME
			: ( defined( 'WP_POWERSUITE_PLUGIN_FILE' )
				? plugin_basename( WP_POWERSUITE_PLUGIN_FILE )
				: 'wp-powersuite/wp-powersuite.php' );
		$plugin_slug = str_replace( '.php', '', basename( $plugin_file ) );
		$plugin_dir  = dirname( $plugin_file );
		$brand_name  = function_exists( 'wp_powersuite_get_plugin_name' )
			? wp_powersuite_get_plugin_name()
			: __( 'WP PowerSuite', 'wp-powersuite' );

		$modal_title   = sprintf(
			/* translators: %s: plugin name */
			__( 'Uninstall %s', 'wp-powersuite' ),
			$brand_name
		);
		$wipe_label    = __( 'Delete all plugin data from the database (settings, module configurations, and related data). This cannot be undone.', 'wp-powersuite' );
		$cancel_text   = __( 'Cancel', 'wp-powersuite' );
		$delete_text   = __( 'Delete plugin', 'wp-powersuite' );
		$close_aria    = __( 'Close', 'wp-powersuite' );
		?>
<style id="wpps-uninstall-modal-styles">
.wpps-uninstall-modal { position: fixed; inset: 0; z-index: 100001; display: none; align-items: center; justify-content: center; padding: 20px; box-sizing: border-box; background: rgba(0,0,0,0.6); }
.wpps-uninstall-modal.is-open { display: flex; }
.wpps-uninstall-modal__content { background: #fff; border-radius: 4px; min-width: 400px; max-width: 520px; width: 100%; box-shadow: 0 4px 24px rgba(0,0,0,0.15); }
.wpps-uninstall-modal__header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid #dcdcde; }
.wpps-uninstall-modal__title { margin: 0; font-size: 18px; font-weight: 600; }
.wpps-uninstall-modal__close { background: none; border: none; padding: 4px; cursor: pointer; color: #787c82; }
.wpps-uninstall-modal__close:hover { color: #1d2327; }
.wpps-uninstall-modal__body { padding: 20px; }
.wpps-uninstall-modal__body p { margin: 0 0 16px 0; font-size: 14px; line-height: 1.5; color: #1d2327; }
.wpps-uninstall-modal__body p:last-of-type { margin-bottom: 0; }
.wpps-uninstall-modal__checkbox-wrap { display: flex; align-items: flex-start; gap: 10px; margin-top: 16px; padding: 12px 14px; background: #f6f7f7; border-left: 4px solid #d63638; border-radius: 0 4px 4px 0; }
.wpps-uninstall-modal__checkbox-wrap input { margin: 3px 0 0 0; }
.wpps-uninstall-modal__checkbox-wrap label { margin: 0; font-size: 13px; line-height: 1.5; cursor: pointer; }
.wpps-uninstall-modal__footer { display: flex; justify-content: flex-end; gap: 10px; padding: 16px 20px; border-top: 1px solid #dcdcde; }
.wpps-deactivate-modal__reasons { margin: 12px 0 0 0; list-style: none; padding: 0; }
.wpps-deactivate-modal__reasons li { margin: 0 0 10px 0; display: flex; align-items: flex-start; gap: 8px; }
.wpps-deactivate-modal__reasons input[type="radio"] { margin: 3px 0 0 0; }
.wpps-deactivate-modal__reasons label { margin: 0; font-size: 14px; line-height: 1.4; cursor: pointer; }
.wpps-deactivate-modal__other-wrap { margin: 10px 0 0 0; padding-left: 24px; }
.wpps-deactivate-modal__other-wrap textarea { width: 100%; min-height: 60px; margin-top: 6px; padding: 8px; box-sizing: border-box; }
.wpps-deactivate-modal__error { margin: 12px 0 0 0; padding: 8px 12px; background: #fcf0f1; border-left: 4px solid #d63638; color: #b32d2e; font-size: 13px; line-height: 1.4; }
</style>
<div id="wpps-uninstall-modal" class="wpps-uninstall-modal" role="dialog" aria-modal="true" aria-labelledby="wpps-uninstall-modal-title" style="display: none;">
	<div class="wpps-uninstall-modal__content">
		<div class="wpps-uninstall-modal__header">
			<h2 id="wpps-uninstall-modal-title" class="wpps-uninstall-modal__title"><?php echo esc_html( $modal_title ); ?></h2>
			<button type="button" class="wpps-uninstall-modal__close" aria-label="<?php echo esc_attr( $close_aria ); ?>"><span class="dashicons dashicons-no-alt" style="font-size: 20px; width: 20px; height: 20px;"></span></button>
		</div>
		<div class="wpps-uninstall-modal__body">
			<p><?php echo esc_html( sprintf(
				/* translators: %s: plugin name */
				__( 'You are about to remove %s from your site. Choose below:', 'wp-powersuite' ),
				$brand_name
			) ); ?></p>
			<div class="wpps-uninstall-modal__checkbox-wrap">
				<input type="checkbox" id="wpps-uninstall-wipe-data" name="wpps_uninstall_wipe_data" value="1" />
				<label for="wpps-uninstall-wipe-data"><?php echo esc_html( $wipe_label ); ?></label>
			</div>
			<p style="margin-top:10px;font-size:13px;color:#646970;"><?php esc_html_e( 'Leave unchecked to only remove the plugin (no data wipe). Check the box to also delete all plugin data from the database.', 'wp-powersuite' ); ?></p>
		</div>
		<div class="wpps-uninstall-modal__footer">
			<button type="button" class="button wpps-uninstall-modal-cancel"><?php echo esc_html( $cancel_text ); ?></button>
			<button type="button" class="button button-primary wpps-uninstall-modal-confirm"><?php echo esc_html( $delete_text ); ?></button>
		</div>
	</div>
</div>

<?php
		$deactivate_title   = __( 'Quick feedback – why are you deactivating?', 'wp-powersuite' );
		$deactivate_intro   = sprintf(
			/* translators: %s: plugin name */
			__( 'If you have a moment, please let us know why you\'re deactivating %s.', 'wp-powersuite' ),
			$brand_name
		);
		$deactivate_skip    = __( 'Skip', 'wp-powersuite' );
		$deactivate_submit = __( 'Submit & Deactivate', 'wp-powersuite' );
		$deactivate_reasons = [
			'temporary'     => __( 'I only need the plugin temporarily', 'wp-powersuite' ),
			'better_plugin' => __( 'I found a better plugin', 'wp-powersuite' ),
			'not_work'      => __( 'I couldn\'t get the plugin to work', 'wp-powersuite' ),
			'broke_site'    => __( 'The plugin broke my site', 'wp-powersuite' ),
			'no_longer'     => __( 'I no longer need the plugin', 'wp-powersuite' ),
			'other'         => __( 'Other', 'wp-powersuite' ),
		];
?>
<div id="wpps-deactivate-modal" class="wpps-uninstall-modal" role="dialog" aria-modal="true" aria-labelledby="wpps-deactivate-modal-title" style="display: none;">
	<div class="wpps-uninstall-modal__content">
		<div class="wpps-uninstall-modal__header">
			<h2 id="wpps-deactivate-modal-title" class="wpps-uninstall-modal__title"><?php echo esc_html( $deactivate_title ); ?></h2>
			<button type="button" class="wpps-deactivate-modal-close" aria-label="<?php echo esc_attr( $close_aria ); ?>"><span class="dashicons dashicons-no-alt" style="font-size: 20px; width: 20px; height: 20px;"></span></button>
		</div>
		<div class="wpps-uninstall-modal__body">
			<p><?php echo esc_html( $deactivate_intro ); ?></p>
			<ul class="wpps-deactivate-modal__reasons">
				<?php foreach ( $deactivate_reasons as $value => $label ) : ?>
				<li>
					<input type="radio" name="wpps_deactivate_reason" id="wpps-reason-<?php echo esc_attr( $value ); ?>" value="<?php echo esc_attr( $value ); ?>" />
					<label for="wpps-reason-<?php echo esc_attr( $value ); ?>"><?php echo esc_html( $label ); ?></label>
				</li>
				<?php endforeach; ?>
			</ul>
			<div class="wpps-deactivate-modal__other-wrap" id="wpps-deactivate-other-wrap" style="display: none;">
				<label for="wpps-deactivate-other-details"><?php esc_html_e( 'Please describe', 'wp-powersuite' ); ?> <span class="required">*</span></label>
				<textarea id="wpps-deactivate-other-details" name="wpps_deactivate_other" rows="3" placeholder="<?php esc_attr_e( 'Your feedback...', 'wp-powersuite' ); ?>"></textarea>
			</div>
			<p id="wpps-deactivate-modal-error" class="wpps-deactivate-modal__error" style="display: none;" role="alert"></p>
		</div>
		<div class="wpps-uninstall-modal__footer">
			<button type="button" class="button wpps-deactivate-modal-skip"><?php echo esc_html( $deactivate_skip ); ?></button>
			<button type="button" class="button button-primary wpps-deactivate-modal-submit"><?php echo esc_html( $deactivate_submit ); ?></button>
		</div>
	</div>
</div>
		<?php
		$nonce = wp_create_nonce( 'wpps_uninstall' );
		$nonce_feedback = wp_create_nonce( 'wpps_deactivation_feedback' );
		?>
<script type="text/javascript">
(function($) {
	'use strict';
	var pluginFile = <?php echo wp_json_encode( $plugin_file ); ?>;
	var pluginSlug = <?php echo wp_json_encode( $plugin_slug ); ?>;
	var pluginDir = <?php echo wp_json_encode( $plugin_dir ); ?>;
	var nonce = <?php echo wp_json_encode( $nonce ); ?>;
	var nonceFeedback = <?php echo wp_json_encode( $nonce_feedback ); ?>;
	var pendingDeleteUrl = null;
	var pendingBulk = false;
	var pendingDeactivateUrl = null;
	var pendingDeactivateBulk = false;

	function openModal() {
		$('#wpps-uninstall-modal').addClass('is-open').show();
		$('#wpps-uninstall-wipe-data').prop('checked', false);
		$('body').addClass('wpps-uninstall-modal-open');
	}
	function closeModal() {
		$('#wpps-uninstall-modal').removeClass('is-open').hide();
		$('body').removeClass('wpps-uninstall-modal-open');
		pendingDeleteUrl = null;
		pendingBulk = false;
	}
	function openDeactivateModal() {
		$('#wpps-deactivate-modal').addClass('is-open').show();
		$('body').addClass('wpps-uninstall-modal-open');
		$('input[name="wpps_deactivate_reason"]').prop('checked', false);
		$('#wpps-deactivate-other-details').val('');
		$('#wpps-deactivate-other-wrap').hide();
	}
	function closeDeactivateModal() {
		$('#wpps-deactivate-modal').removeClass('is-open').hide();
		$('body').removeClass('wpps-uninstall-modal-open');
		pendingDeactivateUrl = null;
		pendingDeactivateBulk = false;
		$('#wpps-deactivate-modal-error').hide().text('');
	}
	function showDeactivateError(message) {
		$('#wpps-deactivate-modal-error').text(message).show();
	}
	function clearDeactivateError() {
		$('#wpps-deactivate-modal-error').hide().text('');
	}
	function detectClientInfo() {
		var ua = navigator.userAgent || '';
		var browser = 'Unknown';
		var os = 'Unknown';

		if (/Edg\//.test(ua)) {
			browser = 'Edge';
		} else if (/OPR\//.test(ua) || /Opera/.test(ua)) {
			browser = 'Opera';
		} else if (/Chrome\//.test(ua) && !/Edg\//.test(ua)) {
			browser = 'Chrome';
		} else if (/Safari\//.test(ua) && !/Chrome\//.test(ua)) {
			browser = 'Safari';
		} else if (/Firefox\//.test(ua)) {
			browser = 'Firefox';
		}

		if (/Windows NT 10/.test(ua)) {
			os = 'Windows 10/11';
		} else if (/Windows NT/.test(ua)) {
			os = 'Windows';
		} else if (/Mac OS X/.test(ua)) {
			os = 'macOS';
		} else if (/Android/.test(ua)) {
			os = 'Android';
		} else if (/iPhone|iPad|iPod/.test(ua)) {
			os = 'iOS';
		} else if (/Linux/.test(ua)) {
			os = 'Linux';
		}

		return { browser: browser, os: os };
	}
	function appendFeedbackParams(url, reason, details, client) {
		var sep = url.indexOf('?') !== -1 ? '&' : '?';
		return url + sep
			+ 'wpps_reason=' + encodeURIComponent(reason)
			+ '&wpps_details=' + encodeURIComponent(details)
			+ '&wpps_feedback=' + encodeURIComponent(nonceFeedback)
			+ '&wpps_client=' + encodeURIComponent(JSON.stringify(client || detectClientInfo()));
	}
	function appendFeedbackFields(form, reason, details, client) {
		$('<input>').attr({ type: 'hidden', name: 'wpps_reason', value: reason }).appendTo(form);
		$('<input>').attr({ type: 'hidden', name: 'wpps_details', value: details }).appendTo(form);
		$('<input>').attr({ type: 'hidden', name: 'wpps_feedback', value: nonceFeedback }).appendTo(form);
		$('<input>').attr({ type: 'hidden', name: 'wpps_client', value: JSON.stringify(client || detectClientInfo()) }).appendTo(form);
	}
	function doDeactivate(sendFeedback) {
		var reason = $('input[name="wpps_deactivate_reason"]:checked').val() || '';
		var details = $('#wpps-deactivate-other-details').val() || '';
		var client = detectClientInfo();
		var url = pendingDeactivateUrl;
		var isBulk = pendingDeactivateBulk;
		closeDeactivateModal();
		if (isBulk) {
			var $form = $('form#bulk-action-form');
			if (sendFeedback) {
				appendFeedbackFields($form, reason, details, client);
			}
			$('<input>').attr({ type: 'hidden', name: 'wpps_deactivate_confirmed', value: '1' }).appendTo($form);
			$form.off('submit').submit();
		} else if (url) {
			if (sendFeedback) {
				url = appendFeedbackParams(url, reason, details, client);
			}
			window.location.href = url;
		}
	}
	function doConfirm() {
		var wipeData = $('#wpps-uninstall-wipe-data').is(':checked');
		$.post(ajaxurl, {
			action: 'wpps_set_delete_preference',
			nonce: nonce,
			delete_data: wipeData ? '1' : '0'
		}).done(function() {
			closeModal();
			if (pendingBulk) {
				$('<input>').attr({ type: 'hidden', name: 'delete_data', value: wipeData ? '1' : '0' }).appendTo('form#bulk-action-form');
				$('form#bulk-action-form').off('submit').submit();
			} else if (pendingDeleteUrl) {
				var sep = pendingDeleteUrl.indexOf('?') !== -1 ? '&' : '?';
				window.location.href = pendingDeleteUrl + sep + 'delete_data=' + (wipeData ? '1' : '0');
			}
		}).fail(function() {
			if (pendingBulk) {
				$('form#bulk-action-form').off('submit').submit();
			} else if (pendingDeleteUrl) {
				window.location.href = pendingDeleteUrl;
			}
			closeModal();
		});
	}

	function decodeHref(href) {
		try { return decodeURIComponent(href); } catch (err) { return href; }
	}
	function hrefMatchesPlugin(href) {
		if (!href) return false;
		var decoded = decodeHref(href);
		var d = decoded.toLowerCase();
		var pf = (pluginFile || '').toLowerCase();
		var ps = (pluginSlug || '').toLowerCase();
		var pd = (pluginDir && pluginDir !== '.') ? pluginDir.toLowerCase() : '';
		return d.indexOf(pf) !== -1 || d.indexOf(ps) !== -1 || (pd && d.indexOf(pd) !== -1) || href.indexOf(encodeURIComponent(pluginFile)) !== -1 || (pd && href.indexOf(pd.replace(/\//g, '%2F')) !== -1);
	}
	function isOurDeleteLink(href) {
		if (!href || !hrefMatchesPlugin(href)) return false;
		var d = decodeHref(href).toLowerCase();
		var hasPluginParam = d.indexOf('plugin=') !== -1 || href.indexOf('plugin%3d') !== -1 || href.indexOf('plugin=') !== -1;
		var isDeleteAction = d.indexOf('action=delete') !== -1 || (d.indexOf('plugins.php') !== -1 && d.indexOf('delete') !== -1 && hasPluginParam);
		return isDeleteAction && hasPluginParam;
	}
	function isOurDeactivateLink(href) {
		return href && href.indexOf('action=deactivate') !== -1 && hrefMatchesPlugin(href);
	}

	document.addEventListener('click', function(e) {
		var el = e.target.nodeType === 1 ? e.target : (e.target.parentElement || e.target);
		var link = el && el.closest ? el.closest('a') : (el ? $(el).closest('a')[0] : null);
		if (!link || !link.href) return;
		var href = link.getAttribute('href');
		if (isOurDeleteLink(href)) {
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
			link.removeAttribute('onclick');
			pendingDeleteUrl = href;
			pendingBulk = false;
			openModal();
			return false;
		}
		if (isOurDeactivateLink(href)) {
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
			pendingDeactivateUrl = href;
			pendingDeactivateBulk = false;
			openDeactivateModal();
			return false;
		}
	}, true);

	$(document).ready(function() {
		$('form#bulk-action-form').on('submit', function(e) {
			var checked = $('input[name="checked[]"]:checked');
			var hasWPPowerSuite = false;
			checked.each(function() {
				var val = $(this).val();
				if (val === pluginFile || (val && (val.indexOf(pluginFile) !== -1 || val.indexOf(pluginSlug) !== -1))) {
					hasWPPowerSuite = true;
					return false;
				}
			});
			if (hasWPPowerSuite && $('select[name="action"]').val() === 'delete-selected') {
				e.preventDefault();
				e.stopPropagation();
				pendingBulk = true;
				pendingDeleteUrl = null;
				openModal();
				return false;
			}
			if (hasWPPowerSuite && $('select[name="action"]').val() === 'deactivate-selected' && !$('input[name="wpps_deactivate_confirmed"]', this).length) {
				e.preventDefault();
				e.stopPropagation();
				pendingDeactivateBulk = true;
				pendingDeactivateUrl = null;
				openDeactivateModal();
				return false;
			}
		});

		$('input[name="wpps_deactivate_reason"]').on('change', function() {
			$('#wpps-deactivate-other-wrap').toggle($(this).val() === 'other');
			clearDeactivateError();
		});
		$('#wpps-deactivate-modal .wpps-deactivate-modal-close').on('click', function() {
			closeDeactivateModal();
		});
		$('#wpps-deactivate-modal').on('click', function(ev) {
			if (ev.target === this) {
				closeDeactivateModal();
			}
		});
		$('.wpps-deactivate-modal-skip').on('click', function() {
			doDeactivate(false);
		});
		$('.wpps-deactivate-modal-submit').on('click', function() {
			var reason = $('input[name="wpps_deactivate_reason"]:checked').val() || '';
			var details = $('#wpps-deactivate-other-details').val().trim();
			if (!reason) {
				showDeactivateError(<?php echo wp_json_encode( __( 'Please select a reason before submitting.', 'wp-powersuite' ) ); ?>);
				return;
			}
			if (reason === 'other' && !details) {
				showDeactivateError(<?php echo wp_json_encode( __( 'Please describe your reason when selecting Other.', 'wp-powersuite' ) ); ?>);
				return;
			}
			doDeactivate(true);
		});
		$(document).on('keydown.wppsDeactivateModal', function(ev) {
			if (ev.key === 'Escape' && $('#wpps-deactivate-modal').hasClass('is-open')) {
				closeDeactivateModal();
			}
		});

		$('#wpps-uninstall-modal .wpps-uninstall-modal__close, .wpps-uninstall-modal-cancel').on('click', closeModal);
		$('#wpps-uninstall-modal').on('click', function(ev) {
			if (ev.target === this) closeModal();
		});
		$('.wpps-uninstall-modal-confirm').on('click', doConfirm);
	});
})(jQuery);
</script>
		<?php
	}
	
	/**
	 * Handle AJAX request to set delete preference
	 */
	public static function handleSetDeletePreference(): void {
		check_ajax_referer( 'wpps_uninstall', 'nonce' );
		
		if ( ! current_user_can( 'delete_plugins' ) ) {
			wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'wp-powersuite' ) ] );
		}
		
		$delete_data = isset( $_POST['delete_data'] ) && $_POST['delete_data'] === '1';

		NetworkScope::updatePluginOption(
			'wp_powersuite_delete_on_uninstall',
			$delete_data ? 'yes' : 'no'
		);
		
		wp_send_json_success( [ 'message' => __( 'Preference saved.', 'wp-powersuite' ) ] );
	}

	/**
	 * Save feedback submitted alongside a deactivate link or bulk action.
	 */
	public static function captureDeactivationFeedbackFromRequest(): void {
		if ( ! is_admin() || wp_doing_ajax() ) {
			return;
		}

		if ( ! self::currentUserCanManagePluginLifecycle() ) {
			return;
		}

		$action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['action'] ) ) : '';
		if ( ! in_array( $action, [ 'deactivate', 'deactivate-selected' ], true ) ) {
			return;
		}

		if ( ! isset( $_REQUEST['wpps_feedback'] ) ) {
			return;
		}

		$nonce = sanitize_text_field( wp_unslash( (string) $_REQUEST['wpps_feedback'] ) );
		if ( ! wp_verify_nonce( $nonce, 'wpps_deactivation_feedback' ) ) {
			return;
		}

		if ( ! self::isDeactivationRequestForOurPlugin() ) {
			return;
		}

		$reason  = isset( $_REQUEST['wpps_reason'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['wpps_reason'] ) ) : '';
		$details = isset( $_REQUEST['wpps_details'] ) ? sanitize_textarea_field( wp_unslash( (string) $_REQUEST['wpps_details'] ) ) : '';
		$client  = self::parseClientPayloadFromRequest();

		self::persistDeactivationFeedback( $reason, $details, $client );
	}

	/**
	 * Handle AJAX request to save deactivation feedback (legacy fallback).
	 */
	public static function handleDeactivationFeedback(): void {
		check_ajax_referer( 'wpps_deactivation_feedback', 'nonce' );

		if ( ! self::currentUserCanManagePluginLifecycle() ) {
			wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'wp-powersuite' ) ] );
		}

		$reason  = isset( $_POST['reason'] ) ? sanitize_key( wp_unslash( $_POST['reason'] ) ) : '';
		$details = isset( $_POST['details'] ) ? sanitize_textarea_field( wp_unslash( $_POST['details'] ) ) : '';
		$client  = self::parseClientPayloadFromRequest();

		if ( ! self::persistDeactivationFeedback( $reason, $details, $client ) ) {
			wp_send_json_error( [ 'message' => __( 'Please select a reason before submitting.', 'wp-powersuite' ) ] );
		}

		wp_send_json_success( [ 'message' => __( 'Thank you for your feedback.', 'wp-powersuite' ) ] );
	}

	/**
	 * @return string Plugin basename used in plugins.php actions.
	 */
	private static function getPluginBasename(): string {
		if ( defined( 'WP_POWERSUITE_PLUGIN_BASENAME' ) ) {
			return WP_POWERSUITE_PLUGIN_BASENAME;
		}

		if ( defined( 'WP_POWERSUITE_PLUGIN_FILE' ) ) {
			return plugin_basename( WP_POWERSUITE_PLUGIN_FILE );
		}

		return 'wp-powersuite/wp-powersuite.php';
	}

	/**
	 * Whether the current deactivate request targets WP PowerSuite.
	 */
	private static function isDeactivationRequestForOurPlugin(): bool {
		$plugin_file = self::getPluginBasename();

		if ( isset( $_REQUEST['plugin'] ) ) {
			$plugin = sanitize_text_field( wp_unslash( (string) $_REQUEST['plugin'] ) );

			return $plugin === $plugin_file;
		}

		if ( ! isset( $_REQUEST['checked'] ) || ! is_array( $_REQUEST['checked'] ) ) {
			return false;
		}

		$checked_list = map_deep( wp_unslash( $_REQUEST['checked'] ), 'sanitize_text_field' );
		if ( ! is_array( $checked_list ) ) {
			return false;
		}

		foreach ( $checked_list as $checked ) {
			if ( (string) $checked === $plugin_file ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * @return array<string, string>
	 */
	private static function parseClientPayloadFromRequest(): array {
		if ( ! isset( $_REQUEST['wpps_client'] ) || ! is_string( $_REQUEST['wpps_client'] ) ) {
			return [];
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON payload; fields sanitized below.
		$raw = wp_unslash( $_REQUEST['wpps_client'] );
		if ( ! is_string( $raw ) || $raw === '' ) {
			return [];
		}

		$data = json_decode( $raw, true );
		if ( ! is_array( $data ) ) {
			return [];
		}

		return [
			'browser' => sanitize_text_field( (string) ( $data['browser'] ?? '' ) ),
			'os'      => sanitize_text_field( (string) ( $data['os'] ?? '' ) ),
		];
	}

	/**
	 * @param array<string, string> $client Browser/OS from the deactivation modal.
	 */
	private static function persistDeactivationFeedback( string $reason, string $details, array $client = [] ): bool {
		$allowed_reasons = [ 'temporary', 'better_plugin', 'not_work', 'broke_site', 'no_longer', 'other' ];
		if ( ! in_array( $reason, $allowed_reasons, true ) ) {
			return false;
		}

		if ( $reason === 'other' && $details === '' ) {
			return false;
		}

		$site_hash = '';
		if ( class_exists( 'WPPS_License_Manager', false ) ) {
			$site_hash = \WPPS_License_Manager::get_instance()->get_site_hash();
		}

		$admin_email = sanitize_email( (string) get_option( 'admin_email' ) );
		$user        = wp_get_current_user();
		$user_email  = ( $user instanceof \WP_User && $user->exists() )
			? sanitize_email( (string) $user->user_email )
			: '';

		$feedback = [
			'reason'         => $reason,
			'details'        => $details,
			'timestamp'      => current_time( 'mysql' ),
			'user_id'        => get_current_user_id(),
			'user_email'     => $user_email,
			'admin_email'    => $admin_email,
			'site_url'       => home_url( '/' ),
			'site_hash'      => $site_hash,
			'plugin_version' => defined( 'WP_POWERSUITE_VERSION' ) ? WP_POWERSUITE_VERSION : '',
			'environment'    => DeactivationFeedbackDiagnostics::collect( $client ),
		];

		NetworkScope::updatePluginOption( 'wp_powersuite_deactivation_feedback', $feedback );
		self::append_feedback_log( $feedback );
		self::maybe_notify_feedback( $feedback );
		self::maybe_send_feedback_webhook( $feedback );

		return true;
	}

	/**
	 * Whether the current user may deactivate/delete this plugin (site or network admin).
	 */
	private static function currentUserCanManagePluginLifecycle(): bool {
		$plugin_file = self::getPluginBasename();

		return current_user_can( 'deactivate_plugin', $plugin_file )
			|| current_user_can( 'delete_plugins' );
	}

	/**
	 * Keep a rolling log of deactivation feedback entries on this site.
	 *
	 * @param array<string,mixed> $feedback Feedback payload.
	 */
	private static function append_feedback_log( array $feedback ): void {
		$log = NetworkScope::getPluginOption( 'wp_powersuite_deactivation_feedback_log', [] );
		if ( ! is_array( $log ) ) {
			$log = [];
		}

		array_unshift( $log, $feedback );
		$log = array_slice( $log, 0, 50 );

		NetworkScope::updatePluginOption( 'wp_powersuite_deactivation_feedback_log', $log );
	}

	/**
	 * Optionally email deactivation feedback to a configured address.
	 *
	 * @param array<string,mixed> $feedback Feedback payload.
	 */
	private static function maybe_notify_feedback( array $feedback ): void {
		$email = '';
		if ( defined( 'WP_POWERSUITE_DEACTIVATION_FEEDBACK_EMAIL' ) && is_email( WP_POWERSUITE_DEACTIVATION_FEEDBACK_EMAIL ) ) {
			$email = (string) WP_POWERSUITE_DEACTIVATION_FEEDBACK_EMAIL;
		}

		$email = (string) apply_filters( 'wp_powersuite_deactivation_feedback_notify_email', $email, $feedback );
		if ( $email === '' || ! is_email( $email ) ) {
			return;
		}

		$brand = function_exists( 'wp_powersuite_get_plugin_name' )
			? wp_powersuite_get_plugin_name()
			: __( 'WP PowerSuite', 'wp-powersuite' );
		$subject = sprintf(
			/* translators: 1: plugin name, 2: site URL */
			__( '[%1$s] Deactivation feedback from %2$s', 'wp-powersuite' ),
			$brand,
			(string) ( $feedback['site_url'] ?? home_url( '/' ) )
		);

		$body = wp_json_encode( $feedback, JSON_PRETTY_PRINT );
		if ( ! is_string( $body ) ) {
			return;
		}

		wp_mail( $email, $subject, $body );
	}

	/**
	 * Optionally POST feedback to a remote webhook (e.g. wppowersuite.com collector).
	 *
	 * @param array<string,mixed> $feedback Feedback payload.
	 */
	private static function maybe_send_feedback_webhook( array $feedback ): void {
		$webhook = '';
		if ( defined( 'WP_POWERSUITE_DEACTIVATION_FEEDBACK_WEBHOOK' ) && WP_POWERSUITE_DEACTIVATION_FEEDBACK_WEBHOOK !== '' ) {
			$webhook = (string) WP_POWERSUITE_DEACTIVATION_FEEDBACK_WEBHOOK;
		}

		$webhook = (string) apply_filters( 'wp_powersuite_deactivation_feedback_webhook_url', $webhook, $feedback );
		if ( $webhook === '' ) {
			return;
		}

		wp_remote_post(
			$webhook,
			[
				'timeout'  => 3,
				'blocking' => false,
				'headers'  => [
					'Content-Type' => 'application/json; charset=utf-8',
				],
				'body'     => wp_json_encode( $feedback ),
			]
		);
	}
}

