<?php
namespace TeknoTok\AiTranslator\Utils;

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

/**
 * Helper class for security encryption/decryption of settings data.
 */
class Crypto {
	/**
	 * Get dynamic site encryption key.
	 *
	 * @return string
	 */
	private static function get_key() {
		$salt = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : 'teknotok-default-encryption-salt';
		return hash( 'sha256', $salt );
	}

	/**
	 * Encrypt a string.
	 *
	 * @param string $data Cleartext string.
	 * @return string Encrypted hex-encoded data.
	 */
	public static function encrypt( $data ) {
		if ( empty( $data ) ) {
			return '';
		}

		$key = self::get_key();
		$iv_length = openssl_cipher_iv_length( 'aes-256-cbc' );
		$iv = openssl_random_pseudo_bytes( $iv_length );
		
		$encrypted = openssl_encrypt( $data, 'aes-256-cbc', $key, 0, $iv );
		
		return base64_encode( $iv . $encrypted );
	}

	/**
	 * Decrypt a string.
	 *
	 * @param string $data Encrypted hex-encoded data.
	 * @return string Cleartext string, or empty on failure.
	 */
	public static function decrypt( $data ) {
		if ( empty( $data ) ) {
			return '';
		}

		$key = self::get_key();
		$decoded = base64_decode( $data );
		$iv_length = openssl_cipher_iv_length( 'aes-256-cbc' );
		
		$iv = substr( $decoded, 0, $iv_length );
		$encrypted = substr( $decoded, $iv_length );
		
		return openssl_decrypt( $encrypted, 'aes-256-cbc', $key, 0, $iv );
	}
}
