<?php

declare(strict_types=1);

if (!defined('ABSPATH')) {
  exit;
}

class KLCNN_Encryption
{
  private static $instance = null;
  private $key;

  public static function get_instance(): self
  {
    if (null === self::$instance) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  private function __construct()
  {
    // Generate or get encryption key
    $this->key = $this->get_encryption_key();
  }

  private function get_encryption_key()
  {
    $key = get_option('klcnn_encryption_key');
    if (!$key) {
      $key = wp_generate_password(64, true, true);
      update_option('klcnn_encryption_key', $key);
    }
    return $key;
  }

  public function encrypt($data)
  {
    if (empty($data)) {
      return '';
    }

    $method = 'aes-256-ctr';
    $ivlen = openssl_cipher_iv_length($method);
    $iv = openssl_random_pseudo_bytes($ivlen);

    $encrypted = openssl_encrypt($data, $method, $this->key, 0, $iv);

    // Return IV + encrypted data
    return base64_encode($iv . $encrypted);
  }

  public function decrypt($data)
  {
    if (empty($data)) {
      return '';
    }

    $data = base64_decode($data);
    $method = 'aes-256-ctr';
    $ivlen = openssl_cipher_iv_length($method);
    $iv = substr($data, 0, $ivlen);
    $encrypted = substr($data, $ivlen);

    return openssl_decrypt($encrypted, $method, $this->key, 0, $iv);
  }
}
