<?php
defined('ABSPATH') || exit;

/**
 * AES-256-CBC encryption for OAuth tokens and API credentials.
 *
 * The 32-byte key is derived from WordPress's AUTH_KEY + SECURE_AUTH_KEY,
 * so encrypted values are tied to this specific WP installation.
 *
 * If those keys are ever rotated, any stored tokens will need to be
 * re-authorised (same behaviour as any WP plugin using salted crypto).
 */
class JRA_Merchant_Encryption {

    private string $key;
    private const  CIPHER = 'AES-256-CBC';

    public function __construct() {
        $raw       = (defined('AUTH_KEY')        ? AUTH_KEY        : '')
                   . (defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : '');
        $this->key = hash('sha256', $raw, true); // raw binary, 32 bytes
    }

    public function encrypt(string $plaintext): string {
        $ivLen     = openssl_cipher_iv_length(self::CIPHER);
        $iv        = random_bytes($ivLen);
        $encrypted = openssl_encrypt($plaintext, self::CIPHER, $this->key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encrypted);
    }

    public function decrypt(string $ciphertext): string {
        $data  = base64_decode($ciphertext, true);
        if ($data === false) {
            return '';
        }
        $ivLen = openssl_cipher_iv_length(self::CIPHER);
        $iv    = substr($data, 0, $ivLen);
        $enc   = substr($data, $ivLen);
        $plain = openssl_decrypt($enc, self::CIPHER, $this->key, OPENSSL_RAW_DATA, $iv);
        return $plain !== false ? $plain : '';
    }
}
