<?php
/**
 * Application-layer encryption for sensitive mobile API payloads.
 * AES-256-CBC (IV prepended) + HKDF-SHA256 session key from the Bearer token (info: qdb-aes).
 */

function qdb_sensitive_envelope(string $plainJson, string $tokenHex): array {
    $key = hkdf_session_key_from_token($tokenHex);
    return [
        'encrypted' => true,
        'payload'   => base64_encode(aes256_cbc_encrypt_bytes($plainJson, $key)),
    ];
}

function qdb_decrypt_sensitive_envelope(array $envelope, string $tokenHex): string {
    if (empty($envelope['encrypted']) || !isset($envelope['payload']) || !is_string($envelope['payload'])) {
        throw new InvalidArgumentException('Invalid encrypted envelope');
    }
    $raw = base64_decode($envelope['payload'], true);
    if ($raw === false) {
        throw new InvalidArgumentException('Invalid base64 payload');
    }
    $key = hkdf_session_key_from_token($tokenHex);
    return aes256_cbc_decrypt_bytes($raw, $key);
}
