<?php

declare(strict_types=1);

/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Service;

final class EncryptOpenSSl
{
    public const METHOD = 'AES-256-CBC';
    public const SECRETKEY = 'viti-core';
    public const SECRETIV = '123456';

    public function encrypt(string $string): string
    {
        $encrypted = openssl_encrypt(
            $string,
            self::METHOD,
            $this->createKey(),
            0,
            $this->createIv(),
        );

        if (false === $encrypted) {
            throw new \RuntimeException('Unable to encrypt the given string.');
        }

        return base64_encode($encrypted);
    }

    public function decrypt(string $string): string
    {
        $decoded = base64_decode($string, true);

        if (false === $decoded) {
            throw new \RuntimeException('Unable to decode the given string from base64.');
        }

        $decrypted = openssl_decrypt(
            $decoded,
            self::METHOD,
            $this->createKey(),
            0,
            $this->createIv(),
        );

        if (false === $decrypted) {
            throw new \RuntimeException('Unable to decrypt the given string.');
        }

        return $decrypted;
    }

    private function createKey(): string
    {
        return hash('sha256', self::SECRETKEY);
    }

    private function createIv(): string
    {
        return substr(hash('sha256', self::SECRETIV), 0, 16);
    }
}
