<?php
/**
 * Crypto Handler
 *
 * Provides AES-256-CBC encryption/decryption utilities for storing tokens securely.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync\includes\common\handlers
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Handlers;

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

/**
 * Class Crypto_Handler
 */
class Crypto_Handler {
	/**
	 * Get encryption key.
	 *
	 * In production, consider sourcing this from a secure location. For now, it resides
	 * in this handler per requirements.
	 */
	private static function get_key(): string {
		// Fallback key (should be rotated and kept secret).
		return 'AZOk6JpZwbfHxDep82gJuR4JU2ZyBoicuN+GxulQwcw=';
	}

	/**
	 * Encrypt plaintext using AES-256-CBC. Returns base64(iv + ciphertext).
	 *
	 * @param string $plaintext Plaintext to encrypt.
	 * @return string
	 */
	public static function encrypt( string $plaintext ): string {
		if ( '' === $plaintext ) {
			return '';
		}
		$key        = substr( hash( 'sha256', self::get_key(), true ), 0, 32 );
		$iv         = random_bytes( 16 );
		$ciphertext = openssl_encrypt( $plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );
		if ( false === $ciphertext ) {
			return '';
		}
		return base64_encode( $iv . $ciphertext );
	}

	/**
	 * Decrypt a base64(iv + ciphertext) string using AES-256-CBC.
	 *
	 * @param string $encoded Encoded string to decrypt.
	 * @return string
	 */
	public static function decrypt( string $encoded ): string {
		if ( '' === $encoded ) {
			return '';
		}
		$raw = base64_decode( $encoded, true );
		if ( false === $raw || strlen( $raw ) < 17 ) {
			return '';
		}
		$iv        = substr( $raw, 0, 16 );
		$ct        = substr( $raw, 16 );
		$key       = substr( hash( 'sha256', self::get_key(), true ), 0, 32 );
		$plaintext = openssl_decrypt( $ct, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );
		return false === $plaintext ? '' : $plaintext;
	}
}
