<?php

function afb_encrypt($plain_text) {
    if (empty($plain_text)) return '';

    $key = hash('sha256', AFB_ENCRYPTION_KEY, true); // raw binary for better compatibility
    $iv  = openssl_random_pseudo_bytes(16);

    $encrypted = openssl_encrypt($plain_text, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    if ($encrypted === false) return '';

    return base64_encode($iv . $encrypted);
}

function afb_decrypt($cipher_text) {
    if (empty($cipher_text)) return '';

    $key  = hash('sha256', AFB_ENCRYPTION_KEY, true);
    $data = base64_decode($cipher_text, true);

    if ($data === false || strlen($data) < 17) return ''; // 16 bytes IV + at least 1 byte of encrypted data

    $iv        = substr($data, 0, 16);
    $encrypted = substr($data, 16);

    $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decrypted !== false ? $decrypted : '';
}
