<?php

if (!class_exists('EasyChat\\Library\\RequestContext', false)) {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'request_context.php';
}

if (!function_exists('easychat_first_header_value')) {
    function easychat_first_header_value($value) {
        $value = trim((string)$value);
        if ($value === '') {
            return '';
        }

        $parts = explode(',', $value);
        return strtolower(trim($parts[0]));
    }
}

if (!function_exists('easychat_is_public_https')) {
    function easychat_is_public_https() {
        $https = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTPS'] ?? '');
        if ($https !== '' && $https !== 'off' && $https !== '0') {
            return true;
        }

        if ((string)(\EasyChat\Library\RequestContext::server()['SERVER_PORT'] ?? '') === '443') {
            return true;
        }

        $scheme = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['REQUEST_SCHEME'] ?? '');
        if ($scheme === 'https') {
            return true;
        }

        $forwarded_proto = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_X_FORWARDED_PROTO'] ?? '');
        if ($forwarded_proto === 'https') {
            return true;
        }

        $forwarded_scheme = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_X_FORWARDED_SCHEME'] ?? '');
        if ($forwarded_scheme === 'https') {
            return true;
        }

        $forwarded_ssl = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_X_FORWARDED_SSL'] ?? '');
        if (in_array($forwarded_ssl, array('on', '1', 'https'), true)) {
            return true;
        }

        $front_end_https = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_FRONT_END_HTTPS'] ?? '');
        if (in_array($front_end_https, array('on', '1', 'https'), true)) {
            return true;
        }

        $forwarded_port = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_X_FORWARDED_PORT'] ?? '');
        if ($forwarded_port === '443') {
            return true;
        }

        $cf_visitor = strtolower((string)(\EasyChat\Library\RequestContext::server()['HTTP_CF_VISITOR'] ?? ''));
        return strpos($cf_visitor, 'https') !== false;
    }
}

if (!function_exists('easychat_public_scheme')) {
    function easychat_public_scheme() {
        return easychat_is_public_https() ? 'https' : 'http';
    }
}

if (!function_exists('easychat_sanitize_host')) {
    function easychat_sanitize_host($host, $fallback = 'localhost') {
        $host = trim((string)$host);
        $host = preg_split("/[\r\n\t]/", $host, 2)[0];
        $host = preg_replace('~^https?://~i', '', $host);
        $host = preg_replace('~/.*$~', '', $host);
        $host = preg_replace('~[^A-Za-z0-9.:\-\[\]]~', '', $host);

        return $host !== '' ? $host : $fallback;
    }
}

if (!function_exists('easychat_public_host')) {
    function easychat_public_host($fallback = 'localhost') {
        $host = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_HOST'] ?? '');

        if ($host === '' || $host === 'localhost') {
            $forwarded_host = easychat_first_header_value(\EasyChat\Library\RequestContext::server()['HTTP_X_FORWARDED_HOST'] ?? '');
            if ($forwarded_host !== '') {
                $host = $forwarded_host;
            }
        }

        return easychat_sanitize_host($host, $fallback);
    }
}

if (!function_exists('easychat_public_base_url')) {
    function easychat_public_base_url($script_name = null) {
        $script_name = $script_name !== null ? (string)$script_name : (string)(\EasyChat\Library\RequestContext::server()['SCRIPT_NAME'] ?? '/index.php');
        $path = rtrim(dirname($script_name), '/\\');
        if ($path === '' || $path === '.') {
            $path = '';
        }

        return easychat_public_scheme() . '://' . easychat_public_host() . $path . '/';
    }
}

if (!function_exists('easychat_asset_base_url')) {
    function easychat_asset_base_url() {
        if (defined('EASYCHAT_ASSET_BASE_URL') && EASYCHAT_ASSET_BASE_URL !== '') {
            return rtrim(EASYCHAT_ASSET_BASE_URL, '/') . '/';
        }

        return defined('HTTP_SERVER') ? rtrim(HTTP_SERVER, '/') . '/' : easychat_public_base_url();
    }
}

if (!function_exists('easychat_asset_url')) {
    function easychat_asset_url($path) {
        return easychat_asset_base_url() . ltrim((string)$path, '/');
    }
}

if (!function_exists('easychat_asset_relative_path')) {
    function easychat_asset_relative_path($path) {
        $relative_path = str_replace('\\', '/', ltrim((string)$path, '/'));
        if ($relative_path === '' || strpos('/' . $relative_path . '/', '/../') !== false) {
            return '';
        }

        return $relative_path;
    }
}

if (!function_exists('easychat_asset_manifest')) {
    function easychat_asset_manifest() {
        static $manifest = null;
        if ($manifest !== null) {
            return $manifest;
        }

        $manifest = array();
        $manifest_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'asset_manifest.php';
        if (is_file($manifest_path)) {
            $loaded = require $manifest_path;
            if (is_array($loaded) && isset($loaded['assets']) && is_array($loaded['assets'])) {
                $manifest = $loaded['assets'];
            }
        }

        return $manifest;
    }
}

if (!function_exists('easychat_asset_version')) {
    function easychat_asset_version($path) {
        $relative_path = easychat_asset_relative_path($path);
        if ($relative_path === '') {
            return defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '1.0.0';
        }

        $manifest = easychat_asset_manifest();
        if (isset($manifest[$relative_path]) && preg_match('/^[a-f0-9]{12,64}$/', (string)$manifest[$relative_path])) {
            return substr((string)$manifest[$relative_path], 0, 12);
        }

        $file_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative_path);
        if (!is_file($file_path)) {
            return defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '1.0.0';
        }

        $hash = @hash_file('sha256', $file_path);
        if (!is_string($hash) || $hash === '') {
            return defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '1.0.0';
        }

        return substr($hash, 0, 12);
    }
}

if (!function_exists('easychat_asset_versioned_url')) {
    function easychat_asset_versioned_url($path) {
        return easychat_asset_url($path) . '?ver=' . rawurlencode(easychat_asset_version($path));
    }
}

if (!function_exists('easychat_html_attrs')) {
    function easychat_html_attrs(array $attrs) {
        $html = '';
        foreach ($attrs as $name => $value) {
            if ($value === null || $value === false) {
                continue;
            }
            $name = preg_replace('/[^A-Za-z0-9_:\-]/', '', (string)$name);
            if ($name === '') {
                continue;
            }
            if ($value === true) {
                $html .= ' ' . $name;
                continue;
            }
            $html .= ' ' . $name . '="' . htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8') . '"';
        }

        return $html;
    }
}

if (!function_exists('easychat_style_tag')) {
    function easychat_style_tag($path, array $attrs = array()) {
        $attrs = array_merge(array(
            'rel' => 'stylesheet',
            'href' => easychat_asset_versioned_url($path),
        ), $attrs);

        return '<link' . easychat_html_attrs($attrs) . '>' . "\n";
    }
}

if (!function_exists('easychat_script_tag')) {
    function easychat_script_tag($path, array $attrs = array()) {
        $attrs = array_merge(array(
            'src' => easychat_asset_versioned_url($path),
        ), $attrs);
        if (!isset($attrs['defer']) && empty($attrs['async'])) {
            $attrs['defer'] = true;
        }

        return '<script' . easychat_html_attrs($attrs) . '></script>' . "\n";
    }
}

if (!function_exists('easychat_preload_tag')) {
    function easychat_preload_tag($path, $as, array $attrs = array()) {
        $url = !empty($attrs['versioned']) ? easychat_asset_versioned_url($path) : easychat_asset_url($path);
        unset($attrs['versioned']);
        $attrs = array_merge(array(
            'rel' => 'preload',
            'href' => $url,
            'as' => (string)$as,
        ), $attrs);

        return '<link' . easychat_html_attrs($attrs) . '>' . "\n";
    }
}

if (!function_exists('easychat_asset_group_version')) {
    function easychat_asset_group_version(array $paths) {
        $parts = array();
        foreach ($paths as $path) {
            $relative_path = easychat_asset_relative_path($path);
            if ($relative_path === '') {
                continue;
            }
            $parts[] = $relative_path . '=' . easychat_asset_version($relative_path);
        }

        sort($parts, SORT_STRING);
        if (!$parts) {
            return defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '1.0.0';
        }

        return substr(hash('sha256', implode('|', $parts)), 0, 12);
    }
}

if (!function_exists('easychat_emoji_asset_paths')) {
    function easychat_emoji_asset_paths() {
        return array(
            'js/emoji/easychat_emoji.js',
        );
    }
}

if (!function_exists('easychat_emoji_asset_version')) {
    function easychat_emoji_asset_version() {
        return easychat_asset_group_version(easychat_emoji_asset_paths());
    }
}

if (!function_exists('easychat_db_prefix')) {
    function easychat_db_prefix() {
        if (defined('EASYCHAT_DB_PREFIX')) {
            return EASYCHAT_DB_PREFIX;
        }

        return defined('DB_PREFIX') ? DB_PREFIX : '';
    }
}

if (!function_exists('easychat_t')) {
    function easychat_t($key, array $params = [], $locale = null) {
        if ($locale === null) {
            $locale = \EasyChat\Library\RequestContext::session()['easychat_locale'] ?? 'ru';
        }
        return \EasyChat\Library\I18n::translate($key, $params, $locale);
    }
}
