<?php
/**
 * Encryption helper functions for 100Prints plugin.
 */

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

/**
 * Encrypt a string value using AES-256-CBC and the site's AUTH_KEY.
 *
 * @param string $value The raw string to encrypt.
 * @return string Encrypted string in base64 format.
 */
function hundred_prints_encrypt( $value ) {
	if ( empty( $value ) ) {
		return '';
	}

	$key = defined( 'AUTH_KEY' ) ? AUTH_KEY : 'default_fallback_key_100prints';
	$iv = random_bytes( 16 );
	$encrypted = openssl_encrypt( $value, 'aes-256-cbc', $key, 0, $iv );
	
	if ( $encrypted === false ) {
		return '';
	}
	
	return base64_encode( $iv . '::' . $encrypted );
}

/**
 * Decrypt a base64-encoded encrypted string using AES-256-CBC and the site's AUTH_KEY.
 *
 * @param string $stored The encrypted string.
 * @return string|null Decrypted raw string, or null on failure.
 */
function hundred_prints_decrypt( $stored ) {
	if ( empty( $stored ) ) {
		return null;
	}

	$decoded = base64_decode( $stored );
	if ( ! $decoded || strpos( $decoded, '::' ) === false ) {
		return null;
	}

	[$iv, $encrypted] = explode( '::', $decoded, 2);
	if ( strlen( $iv ) !== 16 ) {
		return null;
	}

	$key = defined( 'AUTH_KEY' ) ? AUTH_KEY : 'default_fallback_key_100prints';
	$decrypted = openssl_decrypt( $encrypted, 'aes-256-cbc', $key, 0, $iv );

	if ( $decrypted === false ) {
		// Decryption failed (AUTH_KEY changed or key corrupted)
		update_option( '100prints_api_key', '' ); // Auto-clear to prevent infinite issues
		return null;
	}

	return $decrypted;
}
