<?php

if (!function_exists('should_add_lang_parameter')) {
    function should_add_lang_parameter()
    {
        $CI = &get_instance();
        $language_type = $CI->config->item('language_type');
        $total_languages = $CI->config->item('total_languages');
        return (in_array($language_type, ['system', 'default']) && $total_languages > 1);
    }
}

if (!function_exists('get_current_language')) {
    function get_current_language()
    {
        $CI = &get_instance();
        $lang = $CI->input->get('lang');
        // Remove surrounding quotes or encoded characters
        return is_string($lang) ? trim(html_entity_decode($lang, ENT_QUOTES, 'UTF-8'), "'\"") : null;
    }
}

if (!function_exists('add_lang_parameter')) {
    function add_lang_parameter($url)
    {
        if (!should_add_lang_parameter()) {
            return $url;
        }

        $current_lang = get_current_language();
        if (empty($current_lang)) {
            return $url;
        }

        $parts = parse_url($url);
        $query = [];

        if (!empty($parts['query'])) {
            parse_str($parts['query'], $query);
        }

        $query['lang'] = $current_lang;

        $newUrl = '';
        if (!empty($parts['scheme'])) {
            $newUrl .= $parts['scheme'] . '://';
        }
        if (!empty($parts['host'])) {
            $newUrl .= $parts['host'];
        }
        if (!empty($parts['path'])) {
            $newUrl .= $parts['path'];
        }

        if (!empty($query)) {
            $newUrl .= '?' . http_build_query($query);
        }

        return $newUrl;
    }
}

if (!function_exists('add_ref_parameter')) {
    function add_ref_parameter($url, $ref_id = null)
    {
        if ($ref_id === null) {
            $ref_id = isset($_GET['ref']) ? $_GET['ref'] : '';
        }

        if (empty($ref_id)) {
            return $url;
        }

        $separator = (strpos($url, '?') !== false) ? '&' : '?';
        return $url . $separator . 'ref=' . rawurlencode($ref_id);
    }
}

if (!function_exists('base_url')) {
    function base_url($uri = '')
    {
        $CI = &get_instance();
        $base = $CI->config->base_url($uri);
        $url = add_lang_parameter($base);
        $url = add_ref_parameter($url);
        return $url;
    }
}

if (!function_exists('site_url')) {
    function site_url($uri = '')
    {
        $CI = &get_instance();
        $url = $CI->config->site_url($uri);
        $url = add_lang_parameter($url);
        $url = add_ref_parameter($url);
        return $url;
    }
}

if (!function_exists('asset_url')) {
    function asset_url($uri = '')
    {
        $CI = &get_instance();
        return $CI->config->base_url($uri);
    }
}

if (!function_exists('base_url_with_ref')) {
    function base_url_with_ref($uri = '')
    {
        $base = base_url($uri);
        return add_ref_parameter($base);
    }
}
