<?php

declare(strict_types=1);

namespace App\Services\License;

final class ServerFingerprint
{
    public static function collect(array $config = []): array
    {
        $db = $config['db'] ?? [];

        return [
            'host' => (string) (gethostname() ?: ''),
            'os' => PHP_OS_FAMILY,
            'php_uname_n' => (string) php_uname('n'),
            'document_root' => (string) (realpath($_SERVER['DOCUMENT_ROOT'] ?? APP_BASE_PATH) ?: APP_BASE_PATH),
            'app_base' => (string) (realpath(APP_BASE_PATH) ?: APP_BASE_PATH),
            'db_name' => (string) ($db['name'] ?? ''),
            'machine_salt' => self::machineSalt(),
        ];
    }

    public static function value(array $config = []): string
    {
        $payload = self::collect($config);
        ksort($payload);
        return hash('sha256', json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    private static function machineSalt(): string
    {
        $path = APP_BASE_PATH . '/storage/license.machine';
        $dir = dirname($path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }
        if (!is_file($path)) {
            @file_put_contents($path, bin2hex(random_bytes(32)), LOCK_EX);
        }
        return trim((string) (@file_get_contents($path) ?: ''));
    }
}
