<?php

/**
 * Class CryptDecryptData
 *
 * Provides methods for encrypting and decrypting data using OpenSSL.
 */
class CryptDecryptData
{
    private string $clave;
    private string $method;
    private string $iv;

    /**
     * Constructs a new instance.
     *
     * @param string $clave The encryption key
     * @param string $method The encryption method
     * @param string $iv The initialization vector
     */
    public function __construct(string $clave, string $method, string $iv)
    {
        $this->clave = $clave;
        $this->method = $method;
        $this->iv = $iv;
    }

    /**
     * Encrypts data using OpenSSL.
     *
     * @param string $data The data to encrypt
     * @return bool|string The encrypted data or false on error
     */
    public function encrypt(string $data): bool|string
    {
        $ivLength = openssl_cipher_iv_length($this->method);
        $correctIv = substr($this->iv, 0, $ivLength);

        return openssl_encrypt($data, $this->method, $this->clave, false, $correctIv);
    }

    /**
     * Decrypts the provided data.
     *
     * @param string $data The data to decrypt
     * @return bool|string The decrypted data or false on failure
     */
    public function decrypt(string $data): bool|string
    {
        $ivLength = openssl_cipher_iv_length($this->method);
        $correctIv = substr($this->iv, 0, $ivLength);

        return openssl_decrypt($data, $this->method, $this->clave, false, $correctIv);
    }

    /**
     * Generates and returns an initialization vector.
     *
     * @param string $method The encryption method
     * @return string The base64-encoded IV
     */
    private function getIV(string $method): string
    {
        return base64_encode(openssl_random_pseudo_bytes(openssl_cipher_iv_length($method)));
    }
}
