<?php

namespace Prestashop\Module\AddonPayments\Helpers;

use addonpayments;
use ComerciaGlobalPayments\AddonPayments\SDK\Encryption\Cypher\Aes256Ecb;
use Configuration;
use Exception;
use Hashids\Hashids;
use Prestashop\Module\AddonPayments\AddonPaymentsConfig;
use PrestaShopLogger;

/**
 * Implements methods related to encoding and encryption of data.
 */
trait SecurityTrait
{
    public function encrypt(string $unencryptedText, string $key): string
    {
        try {
            return (new Aes256Ecb())->encrypt($unencryptedText, $key);
        } catch (Exception $e) {
            PrestaShopLogger::addLog($e->getMessage(), 4, $e->getCode());
        }

        return $unencryptedText;
    }

    public function decrypt(?string $encryptedText, string $key): ?string
    {
        if (empty($encryptedText)) {
            return null;
        }

        try {
            return (new Aes256Ecb())->decrypt($encryptedText, $key);
        } catch (Exception $e) {
            PrestaShopLogger::addLog($e->getMessage(), 4, $e->getCode());
        }

        return $encryptedText;
    }

    public function encode(...$numbers): string
    {
        return (new Hashids(self::getEncryptionKey()))->encode(...$numbers);
    }

    public function decode($encodedText): array
    {
        return (new Hashids(self::getEncryptionKey()))->decode($encodedText);
    }

    public static function getEncryptionKey(): string
    {
        if (defined('_COOKIE_KEY_') && 0 === strpos(_PS_VERSION_, '1.6')) {
            return _COOKIE_KEY_;
        }

        if (0 === strpos(_PS_VERSION_, '1.7')) {
            $config = include _PS_CACHE_DIR_ . 'appParameters.php';

            return $config['parameters']['secret'] ??
                Configuration::get(AddonPaymentsConfig::POST_INTEGRITY_CHECK);
        }

        return Configuration::get(AddonPaymentsConfig::POST_INTEGRITY_CHECK);
    }
}
