<?php

class Encription
{

    private $chiper = 'aes-256-cbc';


    private $key;


    public function __construct()
    {
        $this->key = $this->getKey();
    }


    public function encryptData($data)
    {
        $ivLength = openssl_cipher_iv_length($this->chiper);
        $iv = openssl_random_pseudo_bytes($ivLength);
        $encrypted = openssl_encrypt($data, $this->chiper, $this->key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }


    public function saveEncryptedJson($filename, $json)
    {
        $encryptedJson = $this->encryptData($json);
        file_put_contents($filename, $encryptedJson);
    }


    public function decryptData($data)
    {
        $data = base64_decode($data);
        $ivLength = openssl_cipher_iv_length($this->chiper);
        $iv = substr($data, 0, $ivLength);
        $encrypted = substr($data, $ivLength);
        return openssl_decrypt($encrypted, $this->chiper, $this->key, 0, $iv);
    }


    public function loadDecryptedJson($filename)
    {
        $encryptedJson = file_get_contents($filename);
        return $this->decryptData($encryptedJson);
    }


    private function getKey()
    {
        $filePath = './composer.json';
        if (!file_exists($filePath)) {
            throw "File not found: $filePath";
        }

        $jsonContent = file_get_contents($filePath);
        $composerData = json_decode($jsonContent, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw "Error decoding JSON: " . json_last_error_msg();
        }

        return $composerData['name'] ?? 'default-key';
    }
}
