<?php
declare(strict_types=1);

namespace App\Services;

class CryptoService
{
    private static function key(): string
    {
        $key = getenv('APP_KEY') ?: '';
        if ($key === '') {
            $key = 'change-this-key';
        }
        return hash('sha256', $key, true);
    }

    public static function encrypt(string $plain): string
    {
        $iv = random_bytes(16);
        $cipher = openssl_encrypt($plain, 'AES-256-CBC', self::key(), OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $cipher);
    }

    public static function decrypt(string $encoded): string
    {
        $bin = base64_decode($encoded, true);
        if ($bin === false || strlen($bin) < 17) {
            return '';
        }
        $iv = substr($bin, 0, 16);
        $cipher = substr($bin, 16);
        $plain = openssl_decrypt($cipher, 'AES-256-CBC', self::key(), OPENSSL_RAW_DATA, $iv);
        return $plain === false ? '' : (string)$plain;
    }
}
