<?php
/**
 * PufferGo 停用调查 - 在用户点击「停用」时弹窗收集原因并保存，删除插件时由 uninstall.php 上报
 *
 * @package PufferGo
 * @since 1.0.0
 */

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

/**
 * Class PufferGo_Deactivation_Survey
 */
class PufferGo_Deactivation_Survey {

	/**
	 * 初始化：仅在插件列表页注入脚本并注册 AJAX
	 */
	public static function init() {
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ), 10 );
		add_action( 'admin_footer-plugins.php', array( __CLASS__, 'render_modal_and_script' ), 10 );
		add_action( 'wp_ajax_puffergo_save_uninstall_reason', array( __CLASS__, 'ajax_save_uninstall_reason' ) );
	}

	/**
	 * 仅在 plugins 页面加载内联依赖（弹窗与逻辑在 footer 输出）
	 */
	public static function enqueue_scripts( $hook ) {
		if ( $hook !== 'plugins.php' ) {
			return;
		}
		// 仅输出 footer 中的 modal + script，无需额外 enqueue
	}

	/**
	 * 在 plugins 页 footer 输出弹窗 HTML 与 JS
	 */
	public static function render_modal_and_script() {
		$plugin_basename   = plugin_basename( defined( 'PUFFERGO_PLUGIN_FILE' ) ? PUFFERGO_PLUGIN_FILE : dirname( __DIR__ ) . '/puffergo.php' );
		$plugins_page_url = admin_url( 'plugins.php' );
		$deactivate_nonce = wp_create_nonce( 'deactivate-plugin_' . $plugin_basename );
		$ajax_url         = admin_url( 'admin-ajax.php' );
		$nonce             = wp_create_nonce( 'puffergo_save_uninstall_reason' );
		$reasons           = array(
			'no_longer_needed' => __( 'I no longer need the plugin', 'puffergo' ),
			'found_alternative' => __( 'I found a better alternative', 'puffergo' ),
			'not_work_as_expected' => __( 'It did not work as expected', 'puffergo' ),
			'temporary' => __( 'Temporary deactivation', 'puffergo' ),
			'other' => __( 'Other', 'puffergo' ),
		);
		?>
		<div id="puffergo-deactivate-modal" class="puffergo-modal-wrap" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:100000; align-items:center; justify-content:center;">
			<div style="background:#fff; padding:24px; border-radius:8px; max-width:420px; width:90%; box-shadow:0 4px 20px rgba(0,0,0,0.15);">
				<h3 style="margin:0 0 16px; font-size:18px;"><?php echo esc_html__( 'Why are you deactivating PufferGo?', 'puffergo' ); ?></h3>
				<select id="puffergo-uninstall-reason" style="width:100%; padding:8px 12px; margin-bottom:12px;">
					<option value=""><?php echo esc_html__( '— Please choose —', 'puffergo' ); ?></option>
					<?php foreach ( $reasons as $value => $label ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>"><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
				<textarea id="puffergo-uninstall-detail" placeholder="<?php echo esc_attr__( 'Optional: tell us more', 'puffergo' ); ?>" rows="3" style="width:100%; padding:8px 12px; margin-bottom:16px; box-sizing:border-box;"></textarea>
				<div style="display:flex; gap:8px; justify-content:flex-end;">
					<button type="button" id="puffergo-deactivate-cancel" class="button"><?php echo esc_html_x( 'Cancel', 'button: cancel and close deactivation survey modal', 'puffergo' ); ?></button>
					<button type="button" id="puffergo-deactivate-submit" class="button button-primary"><?php echo esc_html_x( 'Deactivate', 'button: confirm and proceed to deactivate the plugin', 'puffergo' ); ?></button>
				</div>
			</div>
		</div>
		<script>
		(function() {
			var pluginSlug = <?php echo wp_json_encode( $plugin_basename ); ?>;
			var pluginsPageUrl = <?php echo wp_json_encode( $plugins_page_url ); ?>;
			var deactivateNonce = <?php echo wp_json_encode( $deactivate_nonce ); ?>;
			var ajaxUrl = <?php echo wp_json_encode( $ajax_url ); ?>;
			var nonce = <?php echo wp_json_encode( $nonce ); ?>;

			function showModal() { document.getElementById('puffergo-deactivate-modal').style.display = 'flex'; }
			function hideModal() { document.getElementById('puffergo-deactivate-modal').style.display = 'none'; }

			function submitDeactivate() {
				var f = document.createElement('form');
				f.method = 'POST';
				f.action = pluginsPageUrl;
				var a = document.createElement('input'); a.name = 'action'; a.value = 'deactivate'; f.appendChild(a);
				var p = document.createElement('input'); p.name = 'plugin'; p.value = pluginSlug; f.appendChild(p);
				var n = document.createElement('input'); n.name = '_wpnonce'; n.value = deactivateNonce; f.appendChild(n);
				document.body.appendChild(f);
				f.submit();
			}

			document.querySelectorAll('a[href*="action=deactivate"][href*="plugin=' + encodeURIComponent(pluginSlug) + '"]').forEach(function(a) {
				a.addEventListener('click', function(e) {
					e.preventDefault();
					showModal();
				});
			});

			document.getElementById('puffergo-deactivate-cancel').addEventListener('click', hideModal);
			document.getElementById('puffergo-deactivate-submit').addEventListener('click', function() {
				var reason = document.getElementById('puffergo-uninstall-reason').value;
				var detail = document.getElementById('puffergo-uninstall-detail').value;
				var form = new FormData();
				form.append('action', 'puffergo_save_uninstall_reason');
				form.append('nonce', nonce);
				form.append('reason', reason);
				form.append('reason_detail', detail);
				fetch(ajaxUrl, { method: 'POST', body: form, credentials: 'same-origin' })
					.then(function() { submitDeactivate(); })
					.catch(function() { submitDeactivate(); });
			});
		})();
		</script>
		<?php
	}

	/**
	 * AJAX：保存卸载原因到 option，供 uninstall.php 读取并上报
	 */
	public static function ajax_save_uninstall_reason() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'puffergo_save_uninstall_reason' ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid nonce', 'puffergo' ) ), 403 );
			return;
		}
		$reason = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
		$detail = isset( $_POST['reason_detail'] ) ? sanitize_textarea_field( wp_unslash( $_POST['reason_detail'] ) ) : '';
		update_option( 'puffergo_uninstall_reason', $reason );
		update_option( 'puffergo_uninstall_reason_detail', $detail );
		if ( class_exists( 'PufferGo_Telemetry' ) ) {
			PufferGo_Telemetry::send_deactivate_event( $reason, $detail );
		}
		wp_send_json_success();
	}
}

PufferGo_Deactivation_Survey::init();
