<?php
if (!function_exists('get_active_base_url')) {
    function get_active_base_url()
    {
        if (!isset($GLOBALS['conn'])) {
            return '';
        }

        $sql_config = mysqli_query($GLOBALS['conn'], "SELECT urlweb, urlweb2 FROM `tb_seo` WHERE cuid = 1 LIMIT 1");
        if (!$sql_config) {
            return '';
        }

        $config_data = mysqli_fetch_array($sql_config);
        $main_website_url = $config_data['urlweb'];
        $main_website_url2 = isset($config_data['urlweb2']) ? $config_data['urlweb2'] : '';

        $is_https = false;
        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === '1')) {
            $is_https = true;
        } elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
            $is_https = true;
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            $is_https = true;
        }

        $protocol = $is_https ? "https://" : "http://";
        $current_host = $_SERVER['HTTP_HOST'];

        $urlweb1_normalized = rtrim($main_website_url, '/');
        $urlweb2_normalized = !empty($main_website_url2) ? rtrim($main_website_url2, '/') : '';

        $active_website_url = $main_website_url;

        if (!empty($urlweb2_normalized)) {
            $urlweb2_host = parse_url($urlweb2_normalized, PHP_URL_HOST);
            if ($urlweb2_host && $current_host === $urlweb2_host) {
                $active_website_url = $main_website_url2;
            }
        }

        $urlweb1_host = parse_url($urlweb1_normalized, PHP_URL_HOST);
        if ($urlweb1_host && $current_host === $urlweb1_host) {
            $active_website_url = $main_website_url;
        }

        return rtrim($active_website_url, '/');
    }
}

if (!function_exists('site_url')) {
    function site_url($path = '')
    {
        $path = ltrim($path, '/');
        $base_url = get_active_base_url();

        if (empty($base_url)) {
            return $path;
        }

        $url = $base_url . '/' . $path;

        $is_https = false;
        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === '1')) {
            $is_https = true;
        } elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
            $is_https = true;
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            $is_https = true;
        }

        if ($is_https) {
            $url = str_replace('http://', 'https://', $url);
        }

        return $url;
    }
}
