<?php

/**
 * Class ETM_eTranslation_Utils
 *
 * Utility class for eTranslation engine.
 */
class ETM_eTranslation_Utils {
	/**
	 * Private constructor to prevent instantiation.
	 */
	private function __construct() {}

	/**
	 * Encrypts a plaintext password using AES-256-CBC encryption.
	 *
	 * @param string $plaintext The plaintext password to encrypt.
	 *
	 * @return string The encrypted password in base64 format.
	 */
	public static function encrypt_password( $plaintext ) {
		$parsedUrl = parse_url( get_site_url() );
		$method    = 'AES-256-CBC';
		$key       = hash( 'sha256', $parsedUrl['host'], true );
		$iv        = openssl_random_pseudo_bytes( 16 );

		$ciphertext = openssl_encrypt( $plaintext, $method, $key, OPENSSL_RAW_DATA, $iv );
		$hash       = hash_hmac( 'sha256', $ciphertext . $iv, $key, true );

		return base64_encode( $iv . $hash . $ciphertext );
	}

	/**
	 * Decrypts an encrypted password using AES-256-CBC encryption.
	 *
	 * @param string $base64cipher The encrypted password in base64 format.
	 *
	 * @return string|null The decrypted plaintext password, or null if decryption fails.
	 */
	public static function decrypt_password( $base64cipher ) {
		$parsedUrl        = parse_url( get_site_url() );
		$method           = 'AES-256-CBC';
		$ivHashCiphertext = base64_decode( $base64cipher );
		$iv               = substr( $ivHashCiphertext, 0, 16 );
		$hash             = substr( $ivHashCiphertext, 16, 32 );
		$ciphertext       = substr( $ivHashCiphertext, 48 );
		$key              = hash( 'sha256', $parsedUrl['host'], true );

		// Verify the integrity of the data by checking the hash.
		if ( ! hash_equals( hash_hmac( 'sha256', $ciphertext . $iv, $key, true ), $hash ) ) {
			return null; // The hash does not match, decryption failed.
		}

		return openssl_decrypt( $ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv );
	}
}
