<?php

namespace DigitalApps\PaymentsForAdyen\Admin;

defined('ABSPATH') || exit;

/** Optional feedback for the Free plugin's individual Deactivate action. */
final class Deactivation_Feedback
{
	const ACTION = 'digitalapps_payments_for_adyen_deactivation_feedback';
	const RECIPIENT = 'support@digitalapps.com';
	const MAX_COMMENT_LENGTH = 2000;

	public function register_hooks()
	{
		add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
		add_action('wp_ajax_' . self::ACTION, [$this, 'submit']);
	}

	/** Labels and optional follow-up questions share one translated definition. */
	public static function reasons()
	{
		return [
			'troubleshooting' => [
				'label' => __('I am temporarily troubleshooting', 'digital-apps-payments-for-adyen'),
				'prompt' => __('What are you troubleshooting, and what happened?', 'digital-apps-payments-for-adyen'),
			],
			'setup' => [
				'label' => __('I could not complete the setup', 'digital-apps-payments-for-adyen'),
				'prompt' => __('Which setup step was difficult, and what would have helped?', 'digital-apps-payments-for-adyen'),
			],
			'payments' => [
				'label' => __('Payments were not working', 'digital-apps-payments-for-adyen'),
				'prompt' => __('What happened when you tried to pay? Was this in Test or Live mode? Please describe any error without including payment or customer details.', 'digital-apps-payments-for-adyen'),
			],
			'missing_feature' => [
				'label' => __('A payment method or feature was missing', 'digital-apps-payments-for-adyen'),
				'prompt' => __('Which payment method or feature did you need?', 'digital-apps-payments-for-adyen'),
			],
			'switching' => [
				'label' => __('I am switching to another plugin', 'digital-apps-payments-for-adyen'),
				'prompt' => __('Which plugin are you switching to, and what made it a better fit?', 'digital-apps-payments-for-adyen'),
			],
			'adyen_account' => [
				'label' => __('I do not have a suitable Adyen account', 'digital-apps-payments-for-adyen'),
				'prompt' => __('What prevented you from using an Adyen account with this plugin?', 'digital-apps-payments-for-adyen'),
			],
			'other' => [
				'label' => __('Other', 'digital-apps-payments-for-adyen'),
				'prompt' => __('What made you deactivate the plugin, and how could we improve it?', 'digital-apps-payments-for-adyen'),
			],
		];
	}

	public function enqueue_assets($hook_suffix)
	{
		if ('plugins.php' !== $hook_suffix || !$this->can_submit()) {
			return;
		}

		$handle = 'digitalapps-payments-for-adyen-deactivation-feedback';
		$asset = 'build/admin/deactivation-feedback.js';
		if (!file_exists(DIGITALAPPS_PAYMENTS_FOR_ADYEN_PATH . $asset)) {
			return;
		}

		wp_enqueue_script(
			$handle,
			DIGITALAPPS_PAYMENTS_FOR_ADYEN_URL . $asset,
			['wp-element', 'wp-i18n'],
			filemtime(DIGITALAPPS_PAYMENTS_FOR_ADYEN_PATH . $asset),
			true
		);
		wp_localize_script($handle, 'DigitalAppsAdyenDeactivationFeedback', [
			'ajaxUrl' => admin_url('admin-ajax.php'),
			'action' => self::ACTION,
			'nonce' => wp_create_nonce(self::ACTION),
			'pluginFile' => plugin_basename(DIGITALAPPS_PAYMENTS_FOR_ADYEN_PLUGIN_FILE),
			'version' => DIGITALAPPS_PAYMENTS_FOR_ADYEN_VERSION,
			'recipient' => self::RECIPIENT,
			'maxCommentLength' => self::MAX_COMMENT_LENGTH,
			'reasons' => self::reasons(),
		]);
		wp_set_script_translations($handle, 'digital-apps-payments-for-adyen');
	}

	/** Respect site and network plugin-management permissions. */
	private function can_submit()
	{
		$plugin = plugin_basename(DIGITALAPPS_PAYMENTS_FOR_ADYEN_PLUGIN_FILE);
		if (!current_user_can('deactivate_plugin', $plugin)) {
			return false;
		}
		if (is_plugin_active_for_network($plugin) && !current_user_can('manage_network_plugins')) {
			return false;
		}
		return is_plugin_active($plugin);
	}

	/** Send only an explicitly submitted survey; never send from lifecycle hooks. */
	public function submit()
	{
		if ('POST' !== ($_SERVER['REQUEST_METHOD'] ?? '')) {
			wp_send_json_error(null, 405);
		}
		if (!$this->can_submit()) {
			wp_send_json_error(null, 403);
		}
		$nonce = isset($_POST['nonce']) && is_string($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
		if (!wp_verify_nonce($nonce, self::ACTION)) {
			wp_send_json_error(null, 403);
		}
		if (!isset($_POST['consent']) || '1' !== $_POST['consent']) {
			wp_send_json_error(null, 400);
		}
		$reason = isset($_POST['reason']) && is_string($_POST['reason']) ? wp_unslash($_POST['reason']) : '';
		$reasons = self::reasons();
		if (!isset($reasons[$reason])) {
			wp_send_json_error(null, 400);
		}
		$raw_comment = $_POST['comment'] ?? '';
		if (!is_string($raw_comment) || strlen($raw_comment) > self::MAX_COMMENT_LENGTH * 4) {
			wp_send_json_error(null, 400);
		}
		$comment = sanitize_textarea_field(wp_unslash($raw_comment));
		if (preg_match_all('/[\s\S]/u', $comment) > self::MAX_COMMENT_LENGTH) {
			wp_send_json_error(null, 400);
		}

		// A short, content-free throttle prevents repeated clicks from sending mail.
		$throttle = self::ACTION . '_' . get_current_user_id();
		if (get_transient($throttle)) {
			wp_send_json_error(null, 429);
		}
		set_transient($throttle, 1, MINUTE_IN_SECONDS);

		$message = implode("\n", [
			'Digital Apps Payments for Adyen - optional deactivation feedback',
			'Plugin version: ' . DIGITALAPPS_PAYMENTS_FOR_ADYEN_VERSION,
			'Reason: ' . $reason . ' (' . $reasons[$reason]['label'] . ')',
			'',
			'Comment:',
			'' !== $comment ? $comment : '(No comment supplied)',
		]);
		try {
			$sent = wp_mail(self::RECIPIENT, 'Adyen plugin deactivation feedback', $message, ['Content-Type: text/plain; charset=UTF-8']);
		} catch (\Throwable $error) {
			// Mail integrations must not interrupt deactivation or expose diagnostics.
			$sent = false;
		}
		if (!$sent) {
			wp_send_json_error(null, 502);
		}
		wp_send_json_success();
	}
}
