<?php

namespace SerpIQ\Helpers;

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

final class Crypto {
	private const CIPHER = 'aes-256-cbc';

	/**
	 * Derives a stable binary key from WP salts.
	 *
	 * @return string 32-byte binary key
	 */
	private static function key(): string {
		$material = ( defined( 'AUTH_KEY' ) ? AUTH_KEY : '' ) . '|' . ( defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '' );
		return hash( 'sha256', $material, true );
	}

	/**
	 * @return array{ciphertext:string,iv:string} base64 values
	 */
	public static function encrypt_string( string $plaintext ): array {
		$iv_len = openssl_cipher_iv_length( self::CIPHER );
		$iv = random_bytes( $iv_len );
		$ciphertext = openssl_encrypt( $plaintext, self::CIPHER, self::key(), OPENSSL_RAW_DATA, $iv );

		return array(
			'ciphertext' => base64_encode( $ciphertext ? $ciphertext : '' ),
			'iv'         => base64_encode( $iv ),
		);
	}

	public static function decrypt_string( string $ciphertext_b64, string $iv_b64 ): string {
		if ( '' === $ciphertext_b64 || '' === $iv_b64 ) {
			return '';
		}

		$ciphertext = base64_decode( $ciphertext_b64, true );
		$iv = base64_decode( $iv_b64, true );

		if ( false === $ciphertext || false === $iv ) {
			return '';
		}

		$plaintext = openssl_decrypt( $ciphertext, self::CIPHER, self::key(), OPENSSL_RAW_DATA, $iv );
		return $plaintext ? (string) $plaintext : '';
	}
}

