<?php
// Shared encryption helpers
// Include this in any endpoint that handles passwords/sensitive data
// Uses AES-256-CBC with a server key defined in db.php as EW_SECRET

if (!defined('EW_SECRET')) {
    define('EW_SECRET', 'elegantwork_change_this_32char_key!'); // Change in production
}

function ewEncrypt(string $plain): string {
    if (empty($plain)) return '';
    $iv  = openssl_random_pseudo_bytes(16);
    $enc = openssl_encrypt($plain, 'AES-256-CBC', EW_SECRET, 0, $iv);
    return base64_encode($iv . $enc);
}

function ewDecrypt(string $enc): string {
    if (empty($enc)) return '';
    $raw = base64_decode($enc);
    $iv  = substr($raw, 0, 16);
    $enc = substr($raw, 16);
    return openssl_decrypt($enc, 'AES-256-CBC', EW_SECRET, 0, $iv) ?: '';
}
