<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Api;

use RuntimeException;

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

final class EncryptionService
{
    private const CIPHER = 'aes-256-cbc';

    public function encrypt(string $plaintext, string $secretKey): string
    {
        $ivLen = openssl_cipher_iv_length(self::CIPHER);
        if ($ivLen === false) {
            throw new RuntimeException('Invalid cipher: ' . self::CIPHER);
        }
        $iv = openssl_random_pseudo_bytes($ivLen);

        $ciphertext = openssl_encrypt($plaintext, self::CIPHER, $secretKey, OPENSSL_RAW_DATA, $iv);
        if ($ciphertext === false) {
            throw new RuntimeException('openssl_encrypt failed');
        }

        return base64_encode($iv . $ciphertext);
    }

    public function getSecretKey(string $orderEmail): string
    {
        return hash('sha256', '__' . $orderEmail . '__', true);
    }

    public function getEmailHash(string $orderEmail): string
    {
        return hash('sha256', '--' . $orderEmail . '--');
    }
}
