<?php
/**
 * Encrypt secrets at rest using WordPress salts.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Security;

/**
 * OpenSSL-based encryption helper.
 */
final class Encryption {

	private const METHOD = 'aes-256-cbc';

	/**
	 * Encrypt a string.
	 */
	public static function encrypt( string $plain ): string {
		if ( '' === $plain ) {
			return '';
		}

		$key = self::key();
		$iv  = random_bytes( 16 );
		$raw = openssl_encrypt( $plain, self::METHOD, $key, OPENSSL_RAW_DATA, $iv );

		if ( false === $raw ) {
			return base64_encode( $plain ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
		}

		return base64_encode( $iv . $raw ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
	}

	/**
	 * Decrypt a string.
	 */
	public static function decrypt( string $encoded ): string {
		if ( '' === $encoded ) {
			return '';
		}

		$decoded = base64_decode( $encoded, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
		if ( false === $decoded || strlen( $decoded ) < 17 ) {
			return '';
		}

		$iv  = substr( $decoded, 0, 16 );
		$raw = substr( $decoded, 16 );
		$key = self::key();
		$out = openssl_decrypt( $raw, self::METHOD, $key, OPENSSL_RAW_DATA, $iv );

		return false === $out ? '' : $out;
	}

	/**
	 * Derive encryption key from WordPress salts.
	 */
	private static function key(): string {
		$material = ( defined( 'AUTH_KEY' ) ? AUTH_KEY : '' )
			. ( defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '' )
			. ( defined( 'AUTH_SALT' ) ? AUTH_SALT : '' );

		return hash( 'sha256', $material, true );
	}
}
