<?php

namespace apexl\encryption;

class Encrypt
{
    protected string $cipher = "AES-256-CBC"; // Default cipher

    public function encrypt($plaintext, $encryptionKey): array
    {
        $iv = $this->getEncryptionIv();
        $encrypted = openssl_encrypt($plaintext, $this->cipher, $encryptionKey, 0, base64_decode($iv));

        return [$iv, $encrypted];
    }

    public function decrypt($encryptedText, $iv, $encryptionKey)
    {
        if (!is_null($encryptedText)) {
            return openssl_decrypt($encryptedText, $this->cipher, $encryptionKey, 0, base64_decode($iv));
        }

        return $encryptedText;
    }

    protected function getEncryptionIv(): string
    {
        $ivlen = openssl_cipher_iv_length($this->cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);

        return base64_encode($iv);
    }
}
