<?php
class E2EEncryption {
    private const ALGORITHM = 'aes-256-gcm';
    private const IV_SIZE = 12;
    private const TAG_SIZE = 16;
    private const SHARED_KEY = 'cler_secret_2024_key_encryption';
    
    public static function encrypt($data) {
        try {
            $key = self::getKey();
            $iv = random_bytes(self::IV_SIZE);
            
            $encrypted = openssl_encrypt(
                $data,
                self::ALGORITHM,
                $key,
                OPENSSL_RAW_DATA,
                $iv,
                $tag
            );
            
            $combined = $iv . $encrypted . $tag;
            return base64_encode($combined);
        } catch (Exception $e) {
            return $data;
        }
    }
    
    public static function decrypt($encryptedData) {
        try {
            $combined = base64_decode($encryptedData);
            $iv = substr($combined, 0, self::IV_SIZE);
            $tag = substr($combined, -self::TAG_SIZE);
            $encrypted = substr($combined, self::IV_SIZE, -self::TAG_SIZE);
            
            $key = self::getKey();
            
            $decrypted = openssl_decrypt(
                $encrypted,
                self::ALGORITHM,
                $key,
                OPENSSL_RAW_DATA,
                $iv,
                $tag
            );
            
            return $decrypted !== false ? $decrypted : $encryptedData;
        } catch (Exception $e) {
            return $encryptedData;
        }
    }
    
    private static function getKey() {
        return substr(hash('sha256', self::SHARED_KEY, true), 0, 32);
    }
}
