<?php
namespace EasyChat\Library\Messenger;

use Exception;









class SecretBox {

    public static function encrypt(string $plain, string $install_secret): string {
        if ($plain === '') {
            return '';
        }
        if (!function_exists('openssl_encrypt')) {
            throw new Exception('openssl_required');
        }
        $key = hash('sha256', $install_secret, true);
        $iv = random_bytes(12);
        $tag = '';
        $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
        if ($cipher === false || $tag === '') {
            throw new Exception('secret_encrypt_failed');
        }
        return 'enc:v1:' . base64_encode($iv . $tag . $cipher);
    }

    public static function decrypt(string $value, string $install_secret): string {
        $value = trim($value);
        if ($value === '') {
            return '';
        }
        if (strpos($value, 'enc:v1:') !== 0) {
            return '';
        }
        if (!function_exists('openssl_decrypt')) {
            throw new Exception('openssl_required');
        }
        $raw = base64_decode(substr($value, 7), true);
        if ($raw === false || strlen($raw) < 29) {
            return '';
        }
        $iv = substr($raw, 0, 12);
        $tag = substr($raw, 12, 16);
        $cipher = substr($raw, 28);
        $key = hash('sha256', $install_secret, true);
        $plain = openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
        return is_string($plain) ? $plain : '';
    }

    public static function mask(string $secret): string {
        $secret = trim($secret);
        if ($secret === '') {
            return '';
        }
        if (strlen($secret) <= 10) {
            return '***';
        }
        return substr($secret, 0, 4) . '...' . substr($secret, -4);
    }
}
