<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound
namespace CTL\feedback;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class UsersFeedback {

	private $plugin_url     = CTL_PLUGIN_URL;
	private $plugin_version = CTL_V;
	private $plugin_name    = 'Cool Timeline';
	private $plugin_slug    = 'ctl';
	
	/*
	|-----------------------------------------------------------------|
	|   Use this constructor to fire all actions and filters          |
	|----------------------------------------------------------------|
	*/
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_feedback_scripts' ) );

		add_action( 'wp_ajax_' . $this->plugin_slug . '_submit_deactivation_response', array( $this, 'submit_deactivation_response' ) );
		add_action( 'admin_init', array( $this, 'onInit' ) );
	}
	public function onInit() {
		add_action( 'admin_head', array( $this, 'show_deactivate_feedback_popup' ) );
	}

	/**
	 * Get deactivation feedback reasons shared by the popup and AJAX handler.
	 *
	 * @return array
	 */
	private function get_deactivate_reasons() {
		return array(
			'didnt_work_as_expected'         => array(
				'title'             => esc_html__( "The plugin didn't work as expected", 'cool-timeline' ),
				'input_placeholder' => 'What did you expect?',
			),
			'found_a_better_plugin'          => array(
				'title'             => esc_html( __( 'I found a better plugin', 'cool-timeline' ) ),
				'input_placeholder' => esc_html( __( 'Please share which plugin', 'cool-timeline' ) ),
			),
			'couldnt_get_the_plugin_to_work' => array(
				'title'             => esc_html( __( 'The plugin is not working', 'cool-timeline' ) ),
				'input_placeholder' => 'Please share your issue. So we can fix that for other users.',
			),
			'temporary_deactivation'         => array(
				'title'             => esc_html__( "It's a temporary deactivation", 'cool-timeline' ),
				'input_placeholder' => '',
			),
			'other'                          => array(
				'title'             => esc_html( __( 'Other', 'cool-timeline' ) ),
				'input_placeholder' => esc_html( __( 'Please share the reason', 'cool-timeline' ) ),
			),
		);
	}

	/*
	|-----------------------------------------------------------------|
	|   Enqueue all scripts and styles to required page only          |
	|-----------------------------------------------------------------|
	*/
	function enqueue_feedback_scripts() {
		$screen = get_current_screen();
		if ( isset( $screen ) && 'plugins' === $screen->id ) {
			// phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter
			wp_enqueue_script( __NAMESPACE__ . 'feedback-script', $this->plugin_url . 'admin/cpfm-feedback/js/admin-feedback.js', array( 'jquery' ), $this->plugin_version );
			wp_enqueue_style( 'cool-plugins-feedback-style', $this->plugin_url . 'admin/cpfm-feedback/css/admin-feedback.css', null, $this->plugin_version );
		}
	}

	/*
	|-----------------------------------------------------------------|
	|   HTML for creating feedback popup form                         |
	|-----------------------------------------------------------------|
	*/
	public function show_deactivate_feedback_popup() {
		$screen = get_current_screen();
		if ( ! isset( $screen ) || $screen->id !== 'plugins' ) {
			return;
		}
		$deactivate_reasons = $this->get_deactivate_reasons();

		?>
		<div id="cool-plugins-deactivate-feedback-dialog-wrapper" class="hide-feedback-popup" data-slug="<?php echo esc_attr( $this->plugin_slug ); ?>">
						
			<div class="cool-plugins-deactivation-response">
			<div id="cool-plugins-deactivate-feedback-dialog-header">
				<span id="cool-plugins-feedback-form-title"><?php echo esc_html( __( 'Quick Feedback', 'cool-timeline' ) ); ?></span>
			</div>
			<div id="cool-plugins-loader-wrapper">
				<div class="cool-plugins-loader-container">
					<img class="cool-plugins-preloader" src="<?php echo esc_url( $this->plugin_url ); ?>admin/cpfm-feedback/images/cool-plugins-preloader.gif">
				</div>
			</div>
			<div id="cool-plugins-form-wrapper" class="cool-plugins-form-wrapper-cls">
			<form id="cool-plugins-deactivate-feedback-dialog-form" method="post">
				<?php
				wp_nonce_field( '_cool-plugins_deactivate_feedback_nonce', '_wpnonce' );
				?>
				<input type="hidden" name="action" value="cool-plugins_deactivate_feedback" />
				<div id="cool-plugins-deactivate-feedback-dialog-form-caption"><?php echo esc_html( __( 'If you have a moment, please share why you are deactivating this plugin.', 'cool-timeline' ) ); ?></div>
				<div id="cool-plugins-deactivate-feedback-dialog-form-body">
					<?php
					$reason_key_arr = array( 'didnt_work_as_expected', 'found_a_better_plugin', 'couldnt_get_the_plugin_to_work' );
					foreach ( $deactivate_reasons as $reason_key => $reason ) :
						?>
						<div class="cool-plugins-deactivate-feedback-dialog-input-wrapper">
							<input id="cool-plugins-deactivate-feedback-<?php echo esc_attr( $reason_key ); ?>" class="cool-plugins-deactivate-feedback-dialog-input" type="radio" name="reason_key" value="<?php echo esc_attr( $reason_key ); ?>" />
							<label for="cool-plugins-deactivate-feedback-<?php echo esc_attr( $reason_key ); ?>" class="cool-plugins-deactivate-feedback-dialog-label"><?php echo esc_html( $reason['title'] ); ?></label>
							<?php if ( ! empty( $reason['input_placeholder'] ) ) : ?>
								<textarea class="cool-plugins-feedback-text" type="textarea" name="reason_<?php echo esc_attr( $reason_key ); ?>" placeholder="<?php echo esc_attr( $reason['input_placeholder'] ); ?>"></textarea>
								<?php
									if ( in_array( $reason_key, $reason_key_arr, true ) ) {
									$twae_plugin_url = 'https://wordpress.org/plugins/timeline-widget-addon-for-elementor/';
									?>
								  <div class="cool-plugins-extra-links">
									<?php echo esc_html__( 'Please try ', 'cool-timeline' ); ?><a href="<?php echo esc_url( $twae_plugin_url ); ?>" target="_blank"><?php echo esc_html__( 'Timeline Widget For Elementor', 'cool-timeline' ); ?></a> <?php echo esc_html__( 'plugin.', 'cool-timeline' ); ?>
									</div>
									<?php
								}
								
							endif;
							
							?>
							<?php if ( ! empty( $reason['alert'] ) ) : ?>
								<div class="cool-plugins-feedback-text"><?php echo esc_html( $reason['alert'] ); ?></div>
							<?php endif; ?>
						</div>
					<?php endforeach; ?>

					<input class="cool-plugins-GDPR-data-notice" id="cool-plugins-GDPR-data-notice-<?php echo esc_attr( $this->plugin_slug ); ?>" type="checkbox"><label for="cool-plugins-GDPR-data-notice"><?php echo esc_html__( 'I agree to share anonymous usage data and basic site details (such as server, PHP, and WordPress versions) to support Cool Timeline improvement efforts. Additionally, I allow Cool Plugins to store all information provided through this form and to respond to my inquiry.','cool-timeline' ); ?></label>
					

				</div>
				<div class="cool-plugin-popup-button-wrapper">
					<a class="cool-plugins-button button-deactivate" id="ctl-cool-plugin-submitNdeactivate"><?php echo esc_html__( 'Submit and Deactivate', 'cool-timeline' ); ?></a>
					<a class="cool-plugins-button" id="ctl-cool-plugin-skipNdeactivate"><?php echo esc_html__( 'Skip and Deactivate', 'cool-timeline' ); ?></a>
				</div>
			</form>
			</div>
		   </div>
		</div>
		<?php
	}


	function submit_deactivation_response() {
		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), '_cool-plugins_deactivate_feedback_nonce' ) ) {
			return wp_send_json_error();
			
			
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			return wp_send_json_error( array( 'message' => __( 'Unauthorized access.', 'cool-timeline' ) ) );
			
			
		}

		$reason             = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
		$deactivate_reasons = $this->get_deactivate_reasons();

		$deativation_reason = array_key_exists( $reason, $deactivate_reasons ) ? $reason : 'other';
		
		$sanitized_message = isset( $_POST['message'] ) && sanitize_text_field( wp_unslash( $_POST['message'] ) ) != '' ? sanitize_text_field( wp_unslash( $_POST['message'] ) ) : 'N/A';
		$admin_email       = sanitize_email( get_option( 'admin_email' ) );
		$site_url          = esc_url( site_url() );
		$feedback_url      = CTL_FEEDBACK_API.'wp-json/coolplugins-feedback/v1/feedback' ;
		$initial_version = get_option('ctl_initial_save_version');
		$initial_version = is_string($initial_version) ? sanitize_text_field($initial_version) : 'N/A';
		$install_date      = get_option('ctl-install-date') ?: 'N/A';
		$unique_key        = '31';
		$site_id        	= $site_url . '-' . $install_date . '-' . $unique_key;
		$user_info          = \CoolTimeline::ctl_get_user_info();
		$response          = wp_remote_post(
			$feedback_url,
			array(
				'timeout' => 30,
				'body'    => array(
					'server_info'    => wp_json_encode( $user_info['server_info'] ),
					'extra_details'  => wp_json_encode( $user_info['extra_details'] ),
					'plugin_version' => $this->plugin_version,
					'plugin_name'    => $this->plugin_name,
					'plugin_initial' => $initial_version,
					'reason'         => $deativation_reason,
					'review'         => $sanitized_message,
					'email'          => $admin_email,
					'domain'         => $site_url,
					'site_id'    	 => md5($site_id), 
				),
			)
		);

		wp_send_json_success( array( 'response' => $response ) );
	}
}
new UsersFeedback();
