<?php
/**
 * Deactivation Feedback Handler
 *
 * Processes deactivation feedback submissions and forwards them to miniOrange.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/handlers
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Handlers;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Utils\Logger;

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

/**
 * Class Deactivation_Feedback_Handler
 */
class Deactivation_Feedback_Handler {
	/**
	 * Request type identifier.
	 */
	private const REQUEST_TYPE = 'plugin_deactivation_feedback';

	/**
	 * Logger instance.
	 *
	 * @var Logger
	 */
	private Logger $logger;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->logger = new Logger( 'deactivation-feedback' );
	}

	/**
	 * Submit deactivation feedback to miniOrange endpoint.
	 *
	 * @param string $reason  Selected reason key.
	 * @param string $details Additional details.
	 * @param string $email   Optional email address.
	 * @return array|\WP_Error
	 */
	public function submit_feedback( string $reason, string $details, string $email = '' ) {
		$payload  = $this->build_payload( $reason, $details, $email );
		$endpoint = Plugin_Constants::FEEDBACK_URL;
		$timestamp = round( microtime( true ) * 1000 );
		$timestamp = number_format( $timestamp, 0, '', '' );
		$response = wp_remote_post(
			$endpoint,
			array(
				'headers'     => $this->generate_auth_data( $timestamp )['headers'],
				'body'      => wp_json_encode( $payload ),
				'timeout'   => 20,
				'sslverify' => true,
			)
		);

		if ( is_wp_error( $response ) ) {
			$this->logger->error( 'Deactivation feedback request failed', array( 'error' => $response->get_error_message() ) );
			return $response;
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		if ( $code < 200 || $code >= 300 ) {
			$this->logger->error(
				'Deactivation feedback request returned non-success status',
				array(
					'code'     => $code,
					'response' => wp_remote_retrieve_body( $response ),
				)
			);

			return new \WP_Error(
				'momcs_deactivation_feedback_failed',
				__( 'Failed to submit feedback. Please try again later.', 'multi-channel-for-woocommerce' ),
				array( 'code' => $code )
			);
		}

		return array(
			'message' => __( 'Feedback submitted successfully.', 'multi-channel-for-woocommerce' ),
		);
	}

	/**
	 * Generate authentication data
	 *
	 * @param array  $credentials Customer credentials.
	 * @param string $timestamp   Current timestamp.
	 * @return array Authentication headers and data.
	 */
	private function generate_auth_data( $timestamp ) {
		$string_to_hash = '16555' . $timestamp . 'fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq';
		$hash_value     = hash( 'sha512', $string_to_hash );

		return array(
			'headers' => array(
				'Content-Type'  => 'application/json',
				'Customer-Key'  => '16555',
				'Timestamp'     => $timestamp,
				'Authorization' => $hash_value,
			),
			'body'    => wp_json_encode(
				array(
					'customerId'      => '16555',
					'applicationName' => str_replace( '_plan', '', 'multi-channel-for-woocommerce' ),
				)
			),
		);
	}


	/**
	 * Build the payload for the feedback endpoint.
	 *
	 * @param string $reason  Selected reason key.
	 * @param string $details Additional details.
	 * @param string $email   Optional email address.
	 * @return array<string,string>
	 */
	private function build_payload( string $reason, string $details, string $email ): array {
		$current_user = wp_get_current_user();
		$user_email   = $current_user && isset( $current_user->user_email ) ? (string) $current_user->user_email : '';

		$final_email    = '' !== $email ? $email : ( $user_email ? $user_email : (string) get_option( 'admin_email', '' ) );
		$server  = isset( $_SERVER['SERVER_NAME'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) ) : '';

		$reason_label = $this->format_reason_label( $reason );
		$details_text = '' !== $details ? $details : __( 'No additional details provided.', 'multi-channel-for-woocommerce' );
		
		$query_lines = array(
			'Reason: ' . $reason_label,
			'Details: ' . $details_text,
		);
			
		$content = '<div >Hello, <br><br>First Name :' . $current_user->user_firstname . '<br><br>Last  Name :' . $current_user->user_lastname . '   <br><br>Company :<a href="' . $server . '" target="_blank" >' . $server . '</a><br><br>Email :<a href="mailto:' . $email . '" target="_blank">' . $email . '</a><br><br>Query: ' . implode( "<br><br>", array_filter( $query_lines ) ) . '</div>';
		
		return array(
			'customerKey' => '16555',
			'sendEmail'   => true,
			'email'       => array(
				'customerKey' => '16555',
				'fromEmail'   => $final_email,
				'bccEmail'    => 'info@xecurify.com',
				'fromName'    => 'miniOrange',
				'toEmail'     => 'apisupport@xecurify.com',
				'toName'      => 'apisupport@xecurify.com',
				'subject'     => '[Integrate Amazon for WooCommerce : ' . MOMCS_VERSION . '] Deactivation Feedback',
				'content'     => $content,
			),
		);
	}

	/**
	 * Convert reason key to a human-readable label.
	 *
	 * @param string $reason Reason key.
	 * @return string
	 */
	private function format_reason_label( string $reason ): string {
		$map = array(
			'temporary'         => __( 'I only needed it temporarily', 'multi-channel-for-woocommerce' ),
			'found_better'      => __( 'I found a better plugin', 'multi-channel-for-woocommerce' ),
			'missing_features'  => __( 'Missing features in the plugin', 'multi-channel-for-woocommerce' ),
			'not_working'       => __( 'It is not working as expected', 'multi-channel-for-woocommerce' ),
			'switching_premium' => __( 'I am switching to a premium version', 'multi-channel-for-woocommerce' ),
			'other'             => __( 'Other', 'multi-channel-for-woocommerce' ),
		);

		return $map[ $reason ] ?? __( 'Other', 'multi-channel-for-woocommerce' );
	}
}
