<?php
/**
 * Deactivation feedback modal on the Plugins screen.
 *
 * @package SHC4WC
 */

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

class SHC4WC_Deactivation_Feedback {

	const NOTIFY_EMAIL = 'wordpress.ingenious@gmail.com';

	/** @var self|null */
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_footer', array( $this, 'render_modal' ) );
		add_action( 'wp_ajax_shc4wc_deactivation_feedback', array( $this, 'ajax_send_feedback' ) );
	}

	/**
	 * @param string $hook Admin screen hook suffix.
	 * @return void
	 */
	public function enqueue_assets( $hook ) {
		if ( 'plugins.php' !== $hook ) {
			return;
		}

		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}

		$basename = plugin_basename( SHC4WC_PLUGIN_FILE );
		if ( ! is_plugin_active( $basename ) ) {
			return;
		}

		wp_enqueue_style(
			'shc4wc-deactivation-feedback',
			SHC4WC_PLUGIN_URL . 'assets/css/deactivation-feedback.css',
			array(),
			SHC4WC_VERSION
		);

		wp_enqueue_script(
			'shc4wc-deactivation-feedback',
			SHC4WC_PLUGIN_URL . 'assets/js/deactivation-feedback.js',
			array( 'jquery' ),
			SHC4WC_VERSION,
			true
		);

		wp_localize_script(
			'shc4wc-deactivation-feedback',
			'shc4wcDeactivationFeedback',
			array(
				'pluginBasename' => $basename,
				'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
				'nonce'          => wp_create_nonce( 'shc4wc_deactivation_feedback' ),
				'i18n'           => array(
					'reasonRequired' => __( 'Please share a short reason before submitting.', 'payments-connect-square' ),
					'submitting'     => __( 'Sending…', 'payments-connect-square' ),
					'submit'         => __( 'Submit & deactivate', 'payments-connect-square' ),
				),
			)
		);
	}

	/**
	 * @return void
	 */
	public function render_modal() {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || 'plugins' !== $screen->id ) {
			return;
		}

		if ( ! current_user_can( 'activate_plugins' ) || ! is_plugin_active( plugin_basename( SHC4WC_PLUGIN_FILE ) ) ) {
			return;
		}
		?>
		<div id="shc4wc-deactivation-feedback" class="shc4wc-deactivation-feedback" hidden aria-hidden="true">
			<div class="shc4wc-deactivation-feedback__backdrop" data-shc4wc-deactivation-close></div>
			<div class="shc4wc-deactivation-feedback__dialog" role="dialog" aria-modal="true" aria-labelledby="shc4wc-deactivation-feedback-title">
				<button type="button" class="shc4wc-deactivation-feedback__close" data-shc4wc-deactivation-close aria-label="<?php esc_attr_e( 'Close', 'payments-connect-square' ); ?>">&times;</button>

				<div class="shc4wc-deactivation-feedback__emoji" aria-hidden="true">😢</div>

				<h2 id="shc4wc-deactivation-feedback-title" class="shc4wc-deactivation-feedback__title">
					<?php esc_html_e( 'We are sad to see you go', 'payments-connect-square' ); ?>
				</h2>

				<p class="shc4wc-deactivation-feedback__lead">
					<?php esc_html_e( 'Payments Square Connect has been part of your store. Before you leave, could you tell us what went wrong? Your feedback helps us improve.', 'payments-connect-square' ); ?>
				</p>

				<label class="screen-reader-text" for="shc4wc-deactivation-reason">
					<?php esc_html_e( 'Reason for deactivating', 'payments-connect-square' ); ?>
				</label>
				<textarea
					id="shc4wc-deactivation-reason"
					class="shc4wc-deactivation-feedback__textarea"
					rows="4"
					maxlength="1000"
					placeholder="<?php esc_attr_e( 'For example: setup was confusing, missing a feature, found another plugin…', 'payments-connect-square' ); ?>"
				></textarea>

				<p class="shc4wc-deactivation-feedback__error" hidden></p>

				<div class="shc4wc-deactivation-feedback__actions">
					<button type="button" class="button button-primary shc4wc-deactivation-feedback__submit" id="shc4wc-deactivation-submit">
						<?php esc_html_e( 'Submit & deactivate', 'payments-connect-square' ); ?>
					</button>
					<button type="button" class="shc4wc-deactivation-feedback__skip" data-shc4wc-deactivation-skip>
						<?php esc_html_e( 'Skip and deactivate', 'payments-connect-square' ); ?>
					</button>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * @return void
	 */
	public function ajax_send_feedback() {
		check_ajax_referer( 'shc4wc_deactivation_feedback', 'nonce' );

		if ( ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'payments-connect-square' ) ), 403 );
		}

		$reason = isset( $_POST['reason'] ) ? sanitize_textarea_field( wp_unslash( $_POST['reason'] ) ) : '';
		if ( '' === $reason ) {
			wp_send_json_error( array( 'message' => __( 'Reason is required.', 'payments-connect-square' ) ) );
		}

		$sent = $this->send_feedback_email( $reason );
		if ( ! $sent ) {
			wp_send_json_error( array( 'message' => __( 'Could not send feedback.', 'payments-connect-square' ) ) );
		}

		wp_send_json_success();
	}

	/**
	 * @param string $reason User-provided deactivation reason.
	 * @return bool
	 */
	private function send_feedback_email( $reason ) {
		$admin_email = sanitize_email( get_option( 'admin_email' ) );
		if ( ! is_email( $admin_email ) ) {
			return false;
		}

		$site_url = home_url();
		$subject  = sprintf(
			/* translators: %s: site hostname */
			__( 'Deactivation feedback from %s', 'payments-connect-square' ),
			wp_parse_url( $site_url, PHP_URL_HOST )
		);

		$message = sprintf(
			"%s\n\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n",
			__( 'A user submitted deactivation feedback for Payments Square Connect:', 'payments-connect-square' ),
			__( 'Reason', 'payments-connect-square' ),
			$reason,
			__( 'Site URL', 'payments-connect-square' ),
			$site_url,
			__( 'Admin email', 'payments-connect-square' ),
			$admin_email,
			__( 'Plugin version', 'payments-connect-square' ),
			SHC4WC_VERSION
		);

		$headers = array(
			'Content-Type: text/plain; charset=UTF-8',
			'From: ' . $admin_email,
		);

		return (bool) wp_mail( self::NOTIFY_EMAIL, $subject, $message, $headers );
	}
}
