<?php
/**
 * Deactivation feedback modal for FoodOrd.
 *
 * @package FoodOrd
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Foodord_Deactivation_Feedback.
 */
class Foodord_Deactivation_Feedback {
	private const NONCE_ACTION = 'foodord_deactivation_feedback';
	private const AJAX_ACTION  = 'foodord_send_deactivation_feedback';

	/**
	 * Register hooks.
	 */
	public function init(): void {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ), 20, 1 );
		add_action( 'admin_footer-plugins.php', array( $this, 'render_modal_markup' ) );
		add_action( 'wp_ajax_' . self::AJAX_ACTION, array( $this, 'handle_ajax' ) );
	}

	/**
	 * Enqueue admin assets for plugins screen.
	 *
	 * @param string $hook Current admin hook.
	 */
	public function enqueue_assets( $hook ): void {
		if ( ! is_string( $hook ) || 'plugins.php' !== $hook ) {
			return;
		}

		if ( ! current_user_can( 'deactivate_plugins' ) && ! current_user_can( 'delete_plugins' ) ) {
			return;
		}

		wp_enqueue_style(
			'foodord-deactivation-feedback',
			plugin_dir_url( __FILE__ ) . 'css/foodord-deactivation-feedback.css',
			array(),
			FOODORD_VERSION
		);

		wp_enqueue_script(
			'foodord-deactivation-feedback',
			plugin_dir_url( __FILE__ ) . 'js/foodord-deactivation-feedback.js',
			array(),
			FOODORD_VERSION,
			true
		);

		wp_localize_script(
			'foodord-deactivation-feedback',
			'foodordDeactivationFeedback',
			array(
				'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
				'nonce'      => wp_create_nonce( self::NONCE_ACTION ),
				'pluginFile' => function_exists( 'plugin_basename' ) ? plugin_basename( FOODORD_FILE ) : 'foodord/foodord.php',
			)
		);
	}

	/**
	 * Render modal markup in admin footer.
	 */
	public function render_modal_markup(): void {
		if ( ! current_user_can( 'deactivate_plugins' ) && ! current_user_can( 'delete_plugins' ) ) {
			return;
		}

		$title  = esc_html__( 'We’re sorry to see you go!', 'foodord' );
		$intro  = esc_html__( 'Your feedback is precious to us. Please let us know why you are deactivating FoodOrd so we can improve the experience for everyone.', 'foodord' );
		$cta    = esc_html__( 'Give Feedback & Deactivate', 'foodord' );
		$cancel = esc_html__( 'Keep FoodOrd', 'foodord' );
		$skip   = esc_html__( 'Skip & Deactivate', 'foodord' );

		$reasons = array(
			'setup_complex'   => esc_html__( 'Setup was too complicated', 'foodord' ),
			'technical_error' => esc_html__( 'It didn’t work as expected', 'foodord' ),
			'missing_feature' => esc_html__( 'Missing a specific feature', 'foodord' ),
			'design_mismatch' => esc_html__( 'Design doesn’t fit my brand', 'foodord' ),
			'just_testing'    => esc_html__( 'Just testing for now', 'foodord' ),
			'other'           => esc_html__( 'Other (please specify)', 'foodord' ),
		);

		$other_reasons = array(
			'other_technical_error' => esc_html__( 'Technical issue', 'foodord' ),
			'other_missing_feature' => esc_html__( 'Feature request', 'foodord' ),
		);
		?>
		<div class="foodord-deactivation-feedback" id="foodord-deactivation-feedback" aria-hidden="true" hidden>
			<div class="foodord-deactivation-feedback__backdrop" data-foodord-deactivation-feedback-backdrop></div>
			<div class="foodord-deactivation-feedback__dialog" role="dialog" aria-modal="true"
				aria-labelledby="foodord-deactivation-feedback-title">

				<button type="button" class="foodord-deactivation-feedback__close" data-foodord-deactivation-feedback-cancel
					aria-label="<?php esc_attr_e( 'Close modal', 'foodord' ); ?>">
					<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
						stroke-linecap="round" stroke-linejoin="round">
						<line x1="18" y1="6" x2="6" y2="18"></line>
						<line x1="6" y1="6" x2="18" y2="18"></line>
					</svg>
				</button>

				<form class="foodord-deactivation-feedback__form" data-foodord-deactivation-feedback-form>
					<div class="foodord-deactivation-feedback__header">
						<div class="foodord-deactivation-feedback__visual">
							<div class="foodord-deactivation-feedback__crying-face">
								<div class="foodord-deactivation-feedback__eye foodord-deactivation-feedback__eye--left"></div>
								<div class="foodord-deactivation-feedback__eye foodord-deactivation-feedback__eye--right"></div>
								<div class="foodord-deactivation-feedback__tear foodord-deactivation-feedback__tear--left">
								</div>
								<div class="foodord-deactivation-feedback__tear foodord-deactivation-feedback__tear--right">
								</div>
							</div>
						</div>
						<h2 class="foodord-deactivation-feedback__title" id="foodord-deactivation-feedback-title">
							<?php echo esc_html( $title ); ?>
						</h2>
						<p class="foodord-deactivation-feedback__intro"><?php echo esc_html( $intro ); ?></p>
					</div>

					<div class="foodord-deactivation-feedback__body">
						<fieldset class="foodord-deactivation-feedback__fieldset">
							<legend class="screen-reader-text"><?php echo esc_html( $title ); ?></legend>
							<ul class="foodord-deactivation-feedback__list">
								<?php foreach ( $reasons as $key => $label ) : ?>
									<?php $input_id = 'foodord-deactivation-feedback-reason-' . $key; ?>
									<li class="foodord-deactivation-feedback__item"
										data-foodord-deactivation-feedback-item="<?php echo esc_attr( $key ); ?>">
										<label class="foodord-deactivation-feedback__label"
											for="<?php echo esc_attr( $input_id ); ?>">
											<input type="radio" id="<?php echo esc_attr( $input_id ); ?>"
												name="foodord_deactivation_feedback_reason" value="<?php echo esc_attr( $key ); ?>">
											<span
												class="foodord-deactivation-feedback__radio-text"><?php echo esc_html( $label ); ?></span>
										</label>

										<?php if ( 'missing_feature' === $key ) : ?>
											<div class="foodord-deactivation-feedback__details"
												data-foodord-deactivation-feedback-details="missing_feature" hidden>
												<label class="foodord-deactivation-feedback__details-label"
													for="foodord-deactivation-feedback-details-missing-feature">
													<?php echo esc_html__( 'Which feature are you looking for?', 'foodord' ); ?>
												</label>
												<textarea id="foodord-deactivation-feedback-details-missing-feature" rows="3"
													class="foodord-deactivation-feedback__textarea"
													data-foodord-deactivation-feedback-textarea="missing_feature"
													placeholder="<?php esc_attr_e( 'Tell us more...', 'foodord' ); ?>"></textarea>
											</div>
										<?php endif; ?>

										<?php if ( 'other' === $key ) : ?>
											<div class="foodord-deactivation-feedback__other" data-foodord-deactivation-feedback-other
												hidden>
												<fieldset
													class="foodord-deactivation-feedback__fieldset foodord-deactivation-feedback__fieldset--other">
													<legend class="screen-reader-text">
														<?php echo esc_html__( 'Other reason', 'foodord' ); ?>
													</legend>
													<ul
														class="foodord-deactivation-feedback__list foodord-deactivation-feedback__list--other">
														<?php foreach ( $other_reasons as $other_key => $other_label ) : ?>
															<?php $other_id = 'foodord-deactivation-feedback-other-' . $other_key; ?>
															<li
																class="foodord-deactivation-feedback__item foodord-deactivation-feedback__item--other">
																<label class="foodord-deactivation-feedback__label"
																	for="<?php echo esc_attr( $other_id ); ?>">
																	<input type="radio" id="<?php echo esc_attr( $other_id ); ?>"
																		name="foodord_deactivation_feedback_other_reason"
																		value="<?php echo esc_attr( $other_key ); ?>">
																	<span
																	class="foodord-deactivation-feedback__radio-text"><?php echo esc_html( $other_label ); ?></span>
																</label>
															</li>
														<?php endforeach; ?>
													</ul>
												</fieldset>

												<div class="foodord-deactivation-feedback__details"
													data-foodord-deactivation-feedback-details="other" hidden>
													<label class="foodord-deactivation-feedback__details-label"
														for="foodord-deactivation-feedback-details-other">
															<?php echo esc_html__( 'Please share your thoughts', 'foodord' ); ?>
													</label>
													<textarea id="foodord-deactivation-feedback-details-other" rows="3"
														class="foodord-deactivation-feedback__textarea"
														data-foodord-deactivation-feedback-textarea="other"
															placeholder="<?php esc_attr_e( 'Any feedback is appreciated...', 'foodord' ); ?>"></textarea>
												</div>
											</div>
										<?php endif; ?>
									</li>
								<?php endforeach; ?>
							</ul>
						</fieldset>

						<div class="foodord-deactivation-feedback__error" data-foodord-deactivation-feedback-error hidden></div>
					</div>

					<div class="foodord-deactivation-feedback__footer">
						<button type="button" class="foodord-deactivation-feedback__skip"
							data-foodord-deactivation-feedback-skip>
							<?php echo esc_html( $skip ); ?>
						</button>
						<div class="foodord-deactivation-feedback__main-actions">
							<button type="button" class="foodord-deactivation-feedback__cancel"
								data-foodord-deactivation-feedback-cancel>
								<?php echo esc_html( $cancel ); ?>
							</button>
							<button type="submit" class="foodord-deactivation-feedback__submit button button-primary"
								data-foodord-deactivation-feedback-submit>
								<?php echo esc_html( $cta ); ?>
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<?php
	}

	/**
	 * Handle AJAX feedback submission.
	 */
	public function handle_ajax(): void {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_key( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, self::NONCE_ACTION ) ) {
			wp_send_json_error( array( 'message' => 'invalid_nonce' ), 403 );
		}

		$event = isset( $_POST['event'] ) ? sanitize_key( wp_unslash( $_POST['event'] ) ) : '';
		$event = in_array( $event, array( 'deactivate', 'delete' ), true ) ? $event : 'deactivate';

		if ( 'delete' === $event && ! current_user_can( 'delete_plugins' ) ) {
			wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
		}

		if ( 'deactivate' === $event && ! current_user_can( 'deactivate_plugins' ) ) {
			wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
		}

		$plugin_file          = isset( $_POST['plugin_file'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin_file'] ) ) : '';
		$expected_plugin_file = function_exists( 'plugin_basename' ) ? plugin_basename( FOODORD_FILE ) : 'foodord/foodord.php';
		if ( '' === $plugin_file || $expected_plugin_file !== $plugin_file ) {
			wp_send_json_error( array( 'message' => 'invalid_plugin' ), 400 );
		}

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

		$reason_label       = $this->get_reason_label( $reason );
		$other_reason_label = $this->get_other_reason_label( $other_reason );

		$recipient_email = apply_filters( 'foodord_deactivation_feedback_recipient_email', 'info@foodord.com' );
		$recipient_email = is_string( $recipient_email ) ? sanitize_email( $recipient_email ) : '';
		if ( '' === $recipient_email || ! is_email( $recipient_email ) ) {
			wp_send_json_error( array( 'message' => 'missing_recipient_email' ), 400 );
		}

		$subject = sprintf(
			/* translators: %1$s: plugin name, %2$s: event name */
			__( '[%1$s] %2$s feedback', 'foodord' ),
			'FoodOrd',
			ucfirst( $event )
		);

		$user       = wp_get_current_user();
		$user_login = ( $user instanceof WP_User ) ? $user->user_login : '';
		$user_email = ( $user instanceof WP_User ) ? $user->user_email : '';
		$user_id    = ( $user instanceof WP_User ) ? (int) $user->ID : 0;

		$lines = array(
			'Event: ' . $event,
			'Reason: ' . ( $reason_label ? $reason_label : $reason ),
		);
		if ( '' !== $other_reason ) {
			$lines[] = 'Other reason: ' . ( $other_reason_label ? $other_reason_label : $other_reason );
		}
		if ( '' !== $details ) {
			$lines[] = 'Details: ' . $details;
		}
		$lines[] = 'Site: ' . home_url( '/' );
		$lines[] = 'Plugin: FoodOrd ' . ( defined( 'FOODORD_VERSION' ) ? FOODORD_VERSION : '' );
		$lines[] = 'WordPress: ' . get_bloginfo( 'version' );
		$lines[] = 'PHP: ' . PHP_VERSION;
		if ( '' !== $user_login || '' !== $user_email || 0 !== $user_id ) {
			$lines[] = 'User: ' . trim( $user_login . ' (#' . $user_id . ') ' . $user_email );
		}

		$body = implode( "\n", array_filter( $lines, 'is_string' ) );

		$sent = (bool) wp_mail( $recipient_email, $subject, $body );
		wp_send_json_success( array( 'sent' => $sent ) );
	}

	/**
	 * Get human readable label for a reason key.
	 *
	 * @param string $key Reason key.
	 * @return string
	 */
	private function get_reason_label( string $key ): string {
		$map = array(
			'setup_complex'   => __( 'Could not complete setup / too complicated', 'foodord' ),
			'technical_error' => __( 'Did not work as expected / technical error', 'foodord' ),
			'missing_feature' => __( 'A feature I need is missing (please specify)', 'foodord' ),
			'design_mismatch' => __( 'Design does not match my website/theme', 'foodord' ),
			'just_testing'    => __( 'Just testing / do not need it right now', 'foodord' ),
			'other'           => __( 'Other', 'foodord' ),
		);

		return isset( $map[ $key ] ) ? (string) $map[ $key ] : '';
	}

	/**
	 * Get human readable label for an other reason key.
	 *
	 * @param string $key Other reason key.
	 * @return string
	 */
	private function get_other_reason_label( string $key ): string {
		$map = array(
			'other_technical_error' => __( 'Technical error', 'foodord' ),
			'other_missing_feature' => __( 'Missing feature', 'foodord' ),
		);

		return isset( $map[ $key ] ) ? (string) $map[ $key ] : '';
	}
}
