<?php
/**
 * Simple encryption helpers for Hypodash.
 *
 * These provide symmetric encryption using WP salts as the key material.
 * They intentionally fall back to returning the original value when
 * OpenSSL isn't available or decryption fails so the plugin remains
 * operational on systems without the extension.
 */

if ( ! function_exists( 'hypodash_encrypt' ) ) {
	function hypodash_encrypt( $plaintext ) {
		if ( empty( $plaintext ) ) {
			return '';
		}

		if ( ! function_exists( 'openssl_encrypt' ) ) {
			// OpenSSL not available — return plaintext so nothing breaks.
			return $plaintext;
		}

		if ( defined( 'AUTH_KEY' ) && defined( 'NONCE_SALT' ) ) {
			$key = hash( 'sha256', AUTH_KEY . NONCE_SALT, true );
		} else {
			// If WP salts are not available, try another constant combination,
			// but do not require changes to wp-config.php.
			$key = hash( 'sha256', defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '', true );
		}

		$iv = openssl_random_pseudo_bytes( 16 );
		$cipher = openssl_encrypt( $plaintext, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv );
		if ( $cipher === false ) {
			return $plaintext;
		}
		// Store IV + ciphertext in base64
		return base64_encode( $iv . $cipher );
	}
}

if ( ! function_exists( 'hypodash_decrypt' ) ) {
	function hypodash_decrypt( $data ) {
		if ( empty( $data ) ) {
			return '';
		}

		// If OpenSSL not available, assume value stored as plaintext.
		if ( ! function_exists( 'openssl_decrypt' ) ) {
			return $data;
		}

		$raw = base64_decode( $data, true );
		if ( $raw === false || strlen( $raw ) <= 16 ) {
			// Not a valid ciphertext blob; return original value.
			return $data;
		}

		$iv = substr( $raw, 0, 16 );
		$cipher = substr( $raw, 16 );

		if ( defined( 'AUTH_KEY' ) && defined( 'NONCE_SALT' ) ) {
			$key = hash( 'sha256', AUTH_KEY . NONCE_SALT, true );
		} else {
			$key = hash( 'sha256', defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '', true );
		}

		$plain = openssl_decrypt( $cipher, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv );
		if ( $plain === false ) {
			// Decryption failed — return original to avoid breaking.
			return $data;
		}

		return $plain;
	}
}
