<?php
// Simple encryption helpers for demo/MVP.
// For production, move secrets to env vars and rotate keys.

require_once __DIR__ . '/functions.php';

function app_key(): string {
  $config = require __DIR__ . '/../config/config.php';
  $k = (string)($config['app_key'] ?? '');
  if (strlen($k) < 32) {
    // Keep running for local dev, but strongly warn via exception in production setups.
    $k = str_pad($k, 32, '0');
  }
  return $k;
}

function encrypt_str(string $plaintext): string {
  $key = hash('sha256', app_key(), true);
  $iv = random_bytes(16);
  $cipher = openssl_encrypt($plaintext, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
  if ($cipher === false) throw new Exception('Encryption failed');
  $payload = [
    'iv' => base64_encode($iv),
    'ct' => base64_encode($cipher),
  ];
  return base64_encode(json_encode($payload));
}

function decrypt_str(string $payload): string {
  $key = hash('sha256', app_key(), true);
  $json = json_decode(base64_decode($payload), true);
  if (!is_array($json) || empty($json['iv']) || empty($json['ct'])) return '';
  $iv = base64_decode($json['iv']);
  $ct = base64_decode($json['ct']);
  $plain = openssl_decrypt($ct, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
  return $plain === false ? '' : $plain;
}
