<?php
defined('BASEPATH') OR exit('No direct script access allowed');

if (!function_exists('license_normalize_domain')) {
    function license_normalize_domain($host = NULL)
    {
        $host = $host ?: (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'cli');
        $host = strtolower(trim(preg_replace('/:\\d+$/', '', $host), " .\t\n\r\0\x0B"));
        return $host !== '' ? $host : 'unknown-host';
    }
}

if (!function_exists('license_server_fingerprint')) {
    function license_server_fingerprint(array $options = array())
    {
        $include_ip = isset($options['include_ip']) ? (bool) $options['include_ip'] : TRUE;
        $include_mac = !empty($options['include_mac']);
        $root = defined('FCPATH') ? realpath(FCPATH) : FALSE;
        $docroot = isset($_SERVER['DOCUMENT_ROOT']) ? realpath($_SERVER['DOCUMENT_ROOT']) : FALSE;
        $parts = array(
            'v' => '1',
            'domain' => license_normalize_domain(),
            'document_root' => strtolower(str_replace('\\', '/', $docroot ?: 'unavailable')),
            'install_path' => strtolower(str_replace('\\', '/', $root ?: dirname(BASEPATH))),
            'uname' => function_exists('php_uname') ? trim((string) @php_uname()) : 'unavailable',
            'hostname' => function_exists('gethostname') ? strtolower(trim((string) @gethostname())) : 'unavailable',
        );
        if ($include_ip) {
            $parts['server_ip'] = isset($_SERVER['SERVER_ADDR']) ? trim($_SERVER['SERVER_ADDR']) : 'unavailable';
        }
        if ($include_mac) {
            $parts['mac'] = license_detect_mac_address();
        }
        ksort($parts);
        return hash('sha256', json_encode($parts, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    }
}

if (!function_exists('license_detect_mac_address')) {
    function license_detect_mac_address()
    {
        if (!function_exists('shell_exec')) return 'unavailable';
        $output = strtoupper((string) @shell_exec(PHP_OS_FAMILY === 'Windows' ? 'getmac 2>NUL' : 'ip link 2>/dev/null'));
        return preg_match('/(?:[0-9A-F]{2}[:-]){5}[0-9A-F]{2}/', $output, $m)
            ? strtolower(str_replace('-', ':', $m[0])) : 'unavailable';
    }
}

