<?php
// includes/crypto.php
require_once __DIR__ . '/../config.php';

function encrypt_text(string $plaintext): string {
  $key = substr(hash('sha256', APP_SECRET_KEY, true), 0, 32);
  $iv  = substr(hash('sha256', APP_SECRET_IV, true), 0, 16);
  $cipher = openssl_encrypt($plaintext, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
  return base64_encode($cipher);
}

function decrypt_text(string $cipher_b64): string {
  $key = substr(hash('sha256', APP_SECRET_KEY, true), 0, 32);
  $iv  = substr(hash('sha256', APP_SECRET_IV, true), 0, 16);
  $cipher = base64_decode($cipher_b64);
  $plain  = openssl_decrypt($cipher, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
  return $plain === false ? '' : $plain;
}
