<?php

namespace EstatebudConnect\Utilities;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Services\Estatebud;
use EstatebudConnect\Core\Session;
use EstatebudConnect\Core\Strings;
use EstatebudConnect\Core\Locale;
use EstatebudConnect\Core\Cache;
use EstatebudConnect\Models\Settings;
use EstatebudConnect\Models\Property;
use EstatebudConnect\Models\Project;
use EstatebudConnect\Models\Forms;
use EstatebudConnect\Models\Localizations;
use EstatebudConnect\Models\Field;

class Helper
{
    public static function render_markup_from_views($path, $variables = [], $filter_name = '')
    {
        $views_path = wp_normalize_path(plugin_dir_path(__DIR__) . 'Views/');

        if (empty($filter_name)) {
            $full_path = $views_path . $path;
        } else {
            $full_path = apply_filters($filter_name, $views_path . $path);
        }

        extract($variables);

        return include $full_path;
    }

    public static function image_optimizer($url, $options = [])
    {
        $host = strtolower(wp_parse_url($url, PHP_URL_HOST));
        
        if (!str_contains($host, 'estbd.io')) {
            return $url;
        }

        return rtrim($url . '/' . http_build_query($options, '', ','), '/');
    }

    public static function home_url($path = '', $language = null)
    {
        $home_url = Locale::instance()->get_home_url($language);

        if (!empty($path)) {
            $path = ltrim($path, '/');
            $home_url .= '/' . $path;
        }

        return $home_url;
    }

    public static function email_addresses_to_array($input) {
        $items = [];

        if (is_string($input)) {
            $items = explode(",", $input);
        } elseif (is_array($input)) {
            $items = $input;
        }

        $email_addresses = [];

        foreach ($items as $item) {
            $item = sanitize_email($item);

            if (is_email($item)) {
                $email_addresses[] = $item;
            }
        }

        return $email_addresses;
    }

    public static function get_url($file = '')
    {
        $url = plugins_url($file, plugin_dir_path(__DIR__));

        return $url;
    }

    public static function get_currencies_codes()
    {
        $currencies_data = Estatebud::instance()->cache(Cache::TTL_1D)->get_currency_rates();

        $currency_codes = array_keys($currencies_data['rates'] ?? []);
        $currency_pairs = [];

        foreach ($currency_codes as $code) {
            $currency_pairs[strtolower($code)] = $code;
        }

        return $currency_pairs ?? [];
    }

    public static function get_random_string()
    {
        return substr(bin2hex(random_bytes(3)), 0, 6);
    }

    public static function extract_areas_by_depth($data, $depth = 0, &$result = [])
    {
        foreach ($data as $item) {
            if (!isset($result[$depth])) {
                $result[$depth] = [];
            }

            $result[$depth][] = [
                'value' => $item['id'],
                'label' => $item['name'],
            ];

            if (isset($item['areas'])) {
                self::extract_areas_by_depth($item['areas'], $depth + 1, $result);
            }
        }

        return $result;
    }

    public static function flatten_areas($data, $depth = 0, $parent = 0, &$result = [])
    {
        foreach ($data as $item) {
            $result[] = [
                'value' => $item['id'],
                'label' => $item['name'],
                'parent' => $parent,
                'depth' => $depth,
            ];

            if (isset($item['areas'])) {
                self::flatten_areas($item['areas'], $depth + 1, $item['id'], $result);
            }
        }

        return $result;
    }

    public static function build_option($option, $disabled, $selected)
    {
        return [
            'value' => $option['value'],
            'disabled' => $disabled,
            'selected' => $selected,
            'label' => $option['label'],
        ];
    }

    public static function get_user_ip()
    {
        $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'] ?? ''));

        if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CF_CONNECTING_IP']));
        }

        return $ip;
    }

    public static function generate_uuid4()
    {
        $b = random_bytes(16);
        $b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
        $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
    }

    public static function set_user_session_data($user_session_params = [])
    {
        $session_id = Session::instance()->get();

        if (!self::get_user_session($session_id)) {
            $session_id = self::session_start();
        }

        $session_key = sprintf('%s_%s', Session::COOKIE_NAME, $session_id);
        $session_data = self::get_user_session($session_id);
        $new_session_data = array_merge($session_data, $user_session_params);

        set_transient($session_key, $new_session_data, Session::COOKIE_EXPIRE);

        return $new_session_data;
    }

    public static function get_user_session($session_id = null)
    {
        if (!$session_id) {
            $session_id = Session::instance()->get();
        }

        $session_key = sprintf('%s_%s', Session::COOKIE_NAME, $session_id);
        $user_session = get_transient($session_key);

        return $user_session ?? [];
    }

    public static function get_favorites_by_sharing_token($sharing_token)
    {
        $sharing_key = sprintf('%s_%s', Session::COOKIE_NAME, $sharing_token);
        $sharing_key_data = get_transient($sharing_key);
        $session_id = $sharing_key_data['session_id'] ?? null;

        if ($session_id) {
            $session_key = sprintf('%s_%s', Session::COOKIE_NAME, $session_id);
            $session_data = get_transient($session_key);

            if (is_array($session_data) && isset($session_data['favorites'])) {
                $favorites = is_array($session_data['favorites']) ? $session_data['favorites'] : null;
            }
        }

        return $favorites ?? null;
    }

    public static function session_start($user_session_params = [])
    {
        $session_id = self::generate_uuid4();
        $favorites_sharing_token = self::generate_uuid4();

        $session_key = sprintf('%s_%s', Session::COOKIE_NAME, $session_id);
        $sharing_key = sprintf('%s_%s', Session::COOKIE_NAME, $favorites_sharing_token);

        $user_session_params['favorites_sharing_token'] = $favorites_sharing_token;
        $favorites_params = [
            'session_id' => $session_id,
        ];

        Session::instance()->set($session_id);

        set_transient($session_key, $user_session_params, Session::COOKIE_EXPIRE);
        set_transient($sharing_key, $favorites_params, Session::COOKIE_EXPIRE);

        return $session_id;
    }

    public static function convert_distance($unit_from, $amount)
    {
        $supportedUnits = [
            'yd' => 0.9144,
            'km' => 1000,
            'mi' => 1609.34,
        ];

        $amount = (float) $amount;
        $ratio = $supportedUnits[$unit_from] ?? null;

        if (!$ratio) {
            return 0;
        }

        $meters = round($amount * $ratio);

        if ($meters >= 1000) {
            $distance = round($meters / $supportedUnits['km']) . ' km';
        }

        return $distance ?? $meters . ' m';
    }

    public static function get_locale()
    {
        return Locale::instance()->get_locale();
    }

    public static function get_seo_plugin()
    {
        $plugins = [
            'yoast' => 'wordpress-seo/wp-seo.php',
            'rank-math' => 'seo-by-rank-math/rank-math.php',
            'all-in-one-seo' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
        ];

        foreach ($plugins as $name => $path) {
            if (is_plugin_active($path)) {
                return $name;
            }
        }

        return false;
    }

    public static function get_country_name_from_code($code)
    {
        $code = strtoupper($code);

        $countries = [
            'US' => 'United States',
            'AF' => 'Afghanistan',
            'AL' => 'Albania',
            'DZ' => 'Algeria',
            'AS' => 'American Samoa',
            'AD' => 'Angola',
            'AI' => 'Anguilla',
            'AQ' => 'Antarctica',
            'AG' => 'Antigua and Barbuda',
            'AR' => 'Argentina',
            'AM' => 'Armenia',
            'AW' => 'Aruba',
            'AU' => 'Australia',
            'AT' => 'Austria',
            'AZ' => 'Azerbaijan',
            'BS' => 'Bahamas',
            'BH' => 'Bahrain',
            'BD' => 'Bangladesh',
            'BB' => 'Barbados',
            'BY' => 'Belarus',
            'BE' => 'Belgium',
            'BZ' => 'Belize',
            'BJ' => 'Benin',
            'BM' => 'Bermuda',
            'BT' => 'Bhutan',
            'BO' => 'Bolivia',
            'BA' => 'Bosnia and Herzegowina',
            'BW' => 'Botswana',
            'BV' => 'Bouvet Island',
            'BR' => 'Brazil',
            'IO' => 'British Indian Ocean Territory',
            'BN' => 'Brunei Darussalam',
            'BG' => 'Bulgaria',
            'BF' => 'Burkina Faso',
            'BI' => 'Burundi',
            'KH' => 'Cambodia',
            'CM' => 'Cameroon',
            'CA' => 'Canada',
            'CV' => 'Cabo Verde',
            'KY' => 'Cayman Islands',
            'CF' => 'Central African Republic',
            'TD' => 'Chad',
            'CL' => 'Chile',
            'CN' => 'China',
            'CX' => 'Christmas Island',
            'CC' => 'Cocos (Keeling) Islands',
            'CO' => 'Colombia',
            'KM' => 'Comoros',
            'CG' => 'Congo',
            'CD' => 'Congo, the Democratic Republic of the',
            'CK' => 'Cook Islands',
            'CR' => 'Costa Rica',
            'CI' => "Cote d'Ivoire",
            'HR' => 'Croatia (Hrvatska)',
            'CU' => 'Cuba',
            'CY' => 'Cyprus',
            'CZ' => 'Czech Republic',
            'DK' => 'Denmark',
            'DJ' => 'Djibouti',
            'DM' => 'Dominica',
            'DO' => 'Dominican Republic',
            'TL' => 'East Timor',
            'EC' => 'Ecuador',
            'EG' => 'Egypt',
            'SV' => 'El Salvador',
            'GQ' => 'Equatorial Guinea',
            'ER' => 'Eritrea',
            'EE' => 'Estonia',
            'ET' => 'Ethiopia',
            'FK' => 'Falkland Islands (Malvinas)',
            'FO' => 'Faroe Islands',
            'FJ' => 'Fiji',
            'FI' => 'Finland',
            'FR' => 'France',
            'GF' => 'French Guiana',
            'PF' => 'French Polynesia',
            'TF' => 'French Southern Territories',
            'GA' => 'Gabon',
            'GM' => 'Gambia',
            'GE' => 'Georgia',
            'DE' => 'Germany',
            'GH' => 'Ghana',
            'GI' => 'Gibraltar',
            'GR' => 'Greece',
            'GL' => 'Greenland',
            'GD' => 'Grenada',
            'GP' => 'Guadeloupe',
            'GU' => 'Guam',
            'GT' => 'Guatemala',
            'GN' => 'Guinea',
            'GW' => 'Guinea-Bissau',
            'GY' => 'Guyana',
            'HT' => 'Haiti',
            'HM' => 'Heard and Mc Donald Islands',
            'VA' => 'Holy See (Vatican City State)',
            'HN' => 'Honduras',
            'HK' => 'Hong Kong',
            'HU' => 'Hungary',
            'IS' => 'Iceland',
            'IN' => 'India',
            'ID' => 'Indonesia',
            'IR' => 'Iran (Islamic Republic of)',
            'IQ' => 'Iraq',
            'IE' => 'Ireland',
            'IL' => 'Israel',
            'IT' => 'Italy',
            'JM' => 'Jamaica',
            'JP' => 'Japan',
            'JO' => 'Jordan',
            'KZ' => 'Kazakhstan',
            'KE' => 'Kenya',
            'KI' => 'Kiribati',
            'KP' => "Korea, Democratic People's Republic of",
            'KR' => 'Korea, Republic of',
            'KW' => 'Kuwait',
            'KG' => 'Kyrgyzstan',
            'LA' => "Lao, People's Democratic Republic",
            'LV' => 'Latvia',
            'LB' => 'Lebanon',
            'LS' => 'Lesotho',
            'LR' => 'Liberia',
            'LY' => 'Libyan Arab Jamahiriya',
            'LI' => 'Liechtenstein',
            'LT' => 'Lithuania',
            'LU' => 'Luxembourg',
            'MO' => 'Macao',
            'MK' => 'Macedonia, The Former Yugoslav Republic of',
            'MG' => 'Madagascar',
            'MW' => 'Malawi',
            'MY' => 'Malaysia',
            'MV' => 'Maldives',
            'ML' => 'Mali',
            'MT' => 'Malta',
            'MH' => 'Marshall Islands',
            'MQ' => 'Martinique',
            'MR' => 'Mauritania',
            'MU' => 'Mauritius',
            'YT' => 'Mayotte',
            'MX' => 'Mexico',
            'FM' => 'Micronesia, Federated States of',
            'MD' => 'Moldova, Republic of',
            'MC' => 'Monaco',
            'MN' => 'Mongolia',
            'MS' => 'Montserrat',
            'MA' => 'Morocco',
            'MZ' => 'Mozambique',
            'MM' => 'Myanmar',
            'NA' => 'Namibia',
            'NR' => 'Nauru',
            'NP' => 'Nepal',
            'NL' => 'Netherlands',
            'AN' => 'Netherlands Antilles',
            'NC' => 'New Caledonia',
            'NZ' => 'New Zealand',
            'NI' => 'Nicaragua',
            'NE' => 'Niger',
            'NG' => 'Nigeria',
            'NU' => 'Niue',
            'NF' => 'Norfolk Island',
            'MP' => 'Northern Mariana Islands',
            'NO' => 'Norway',
            'OM' => 'Oman',
            'PK' => 'Pakistan',
            'PW' => 'Palau',
            'PA' => 'Panama',
            'PG' => 'Papua New Guinea',
            'PY' => 'Paraguay',
            'PE' => 'Peru',
            'PH' => 'Philippines',
            'PN' => 'Pitcairn',
            'PL' => 'Poland',
            'PT' => 'Portugal',
            'PR' => 'Puerto Rico',
            'QA' => 'Qatar',
            'RE' => 'Reunion',
            'RO' => 'Romania',
            'RU' => 'Russian Federation',
            'RW' => 'Rwanda',
            'KN' => 'Saint Kitts and Nevis',
            'LC' => 'Saint Lucia',
            'VC' => 'Saint Vincent and the Grenadines',
            'WS' => 'Samoa',
            'SM' => 'San Marino',
            'ST' => 'Sao Tome and Principe',
            'SA' => 'Saudi Arabia',
            'SN' => 'Senegal',
            'SC' => 'Seychelles',
            'SL' => 'Sierra Leone',
            'SG' => 'Singapore',
            'SK' => 'Slovakia (Slovak Republic)',
            'SI' => 'Slovenia',
            'SB' => 'Solomon Islands',
            'SO' => 'Somalia',
            'ZA' => 'South Africa',
            'GS' => 'South Georgia and the South Sandwich Islands',
            'ES' => 'Spain',
            'LK' => 'Sri Lanka',
            'SH' => 'St. Helena',
            'PM' => 'St. Pierre and Miquelon',
            'SD' => 'Sudan',
            'SR' => 'Suriname',
            'SJ' => 'Svalbard and Jan Mayen Islands',
            'SZ' => 'Swaziland',
            'SE' => 'Sweden',
            'CH' => 'Switzerland',
            'SY' => 'Syrian Arab Republic',
            'TW' => 'Taiwan, Province of China',
            'TJ' => 'Tajikistan',
            'TZ' => 'Tanzania, United Republic of',
            'TH' => 'Thailand',
            'TG' => 'Togo',
            'TK' => 'Tokelau',
            'TO' => 'Tonga',
            'TT' => 'Trinidad and Tobago',
            'TN' => 'Tunisia',
            'TR' => 'Turkey',
            'TM' => 'Turkmenistan',
            'TC' => 'Turks and Caicos Islands',
            'TV' => 'Tuvalu',
            'UG' => 'Uganda',
            'UA' => 'Ukraine',
            'AE' => 'United Arab Emirates',
            'GB' => 'United Kingdom',
            'UM' => 'United States Minor Outlying Islands',
            'UY' => 'Uruguay',
            'UZ' => 'Uzbekistan',
            'VU' => 'Vanuatu',
            'VE' => 'Venezuela',
            'VN' => 'Vietnam',
            'VG' => 'Virgin Islands (British)',
            'VI' => 'Virgin Islands (U.S.)',
            'WF' => 'Wallis and Futuna Islands',
            'EH' => 'Western Sahara',
            'YE' => 'Yemen',
            'YU' => 'Serbia',
            'ZM' => 'Zambia',
            'ZW' => 'Zimbabwe',
        ];

        return $countries[$code] ?? $code;
    }

    public static function generate_field_name($field)
    {
        $field_obj = new Field($field);
        $field_type = $field_obj->get_type() ?: 'text';
        $field_label = $field_obj->get_label();
        $field_placeholder = $field_obj->get_placeholder();

        if (!empty($field_label)) {
            return Helper::slugify($field_label, '_');
        }

        if (!empty($field_placeholder)) {
            return Helper::slugify($field_placeholder, '_');
        }

        return Helper::unique_id($field_type . '_', 12);
    }

    public static function get_translatable_dynamic_terms()
    {
        $translatable_terms = [];

        $property_listing_settings = (new Property)->get_settings();

        if (!empty($property_listing_settings['legal_disclaimer'])) {
            $translatable_terms[] = [
                'key' => "property_listing.legal_disclaimer",
                'value' => $property_listing_settings['legal_disclaimer'],
            ];
        }

        $project_listing_settings = (new Project)->get_settings();

        if (!empty($project_listing_settings['legal_disclaimer'])) {
            $translatable_terms[] = [
                'key' => "project_listing.legal_disclaimer",
                'value' => $project_listing_settings['legal_disclaimer'],
            ];
        }

        $forms_model = Forms::instance();
        $all_forms = $forms_model->get_all_forms();

        foreach ($all_forms as $form) {
            $form_id = $form['id'];

            if (!empty($form['button_label'])) {
                $translatable_terms[] = [
                    'key' => "form.{$form_id}.button.label",
                    'value' => $form['button_label'],
                ];
            }

            $fields = $form['fields'] ?? [];

            foreach ($fields as $field_index => $field) {
                $field_obj = new Field($field);
                $field_id = $field_obj->get_id();

                $field_label = $field_obj->get_label();
                if (!empty($field_label)) {
                    $translatable_terms[] = [
                        'key' => sprintf("form.%s.field.%s.label", $form_id, $field_id),
                        'value' => $field_label,
                    ];
                }

                $field_placeholder = $field_obj->get_placeholder();
                if (!empty($field_placeholder)) {
                    $translatable_terms[] = [
                        'key' => sprintf("form.%s.field.%s.placeholder", $form_id, $field_id),
                        'value' => $field_placeholder,
                    ];
                }

                $field_type = $field_obj->get_type();
                if (in_array($field_type, ['select', 'radio', 'checkbox'])) {
                    $options_array = $field_obj->get_options();

                    foreach ($options_array as $option_item) {
                        $label = $option_item['label'] ?? '';
                        $value = $option_item['value'] ?? '';

                        if ($label === '') {
                            continue;
                        }

                        $option_hash = hash('xxh32', $label);
                        $translatable_terms[] = [
                            'key' => sprintf("form.%s.field.%s.option.%s.label", $form_id, $field_id, $option_hash),
                            'value' => $label,
                        ];
                    }
                }
            }
        }

        return $translatable_terms;
    }

    public static function get_term_type_label($key)
    {
        if (strpos($key, '.field.') !== false) {
            if (strpos($key, '.option.') !== false) {
                return 'Field option';
            } elseif (strpos($key, '.placeholder') !== false) {
                return 'Field placeholder';
            } elseif (strpos($key, '.label') !== false) {
                return 'Field label';
            }
        } elseif (strpos($key, '.button.') !== false) {
            return 'Button text';
        }

        return 'Text';
    }

    public static function get_locale_display_name($locale, $fallback = '')
    {
        if (!extension_loaded('intl')) {
            return $fallback;
        }

        $localizedName = \Locale::getDisplayLanguage($locale, Helper::get_locale());
        $nativeName = \Locale::getDisplayLanguage($locale, $locale);

        if ($nativeName !== $localizedName) {
            $localizedName .= ' (' . $nativeName . ')';
        }

        return $localizedName;
    }

    public static function term($key, $count = null, $language = null)
    {
        $active_language = Helper::get_locale();

        if (is_null($count)) {
            $count = 1;
        }

        if (is_null($language)) {
            $language = $active_language;
        }

        $term = Localizations::instance()->get_localization($key, $count, $language);

        if (empty($term)) {
            $term = Locale::instance()->get_term($key, $count, $language);
        }

        if (empty($term)) {
            $term = Localizations::instance()->get_localization($key, $count, 'en');
        }

        if (empty($term)) {
            $term = Locale::instance()->get_term($key, $count, 'en');
        }

        return $term ?? $key;
    }

    public static function get_term_from_array($array, $language = null)
    {
        $active_language = Helper::get_locale();

        if (!is_array($array)) {
            $array = [];
        }

        if (is_null($language)) {
            $language = Helper::get_locale();
        }

        if (isset($array['translations'])) {
            $array = $array['translations'];
        }

        $minor_language = substr($language, 0, 2);

        foreach ([$language, 'en'] as $code) {
            foreach ($array as $key => $value) {
                $minor_response_language = substr($key, 0, 2);

                if ($code == $key || $minor_language == $minor_response_language) {
                    return $value;
                }
            }
        }

        return '';
    }

    public static function format_price($data, $exchange_rates = null)
    {
        if (empty($data['price'])) {
            return null;
        }

        if (is_null($exchange_rates)) {
            $user_session = Helper::get_user_session();
            $currency = strtoupper($user_session['currency'] ?? $data['currency']);

            $currency_data = Helper::get_currency_data($data['currency'], $currency);
            $exchange_rates = $currency_data['exchange_rates'];
        }

        $formatted_price = '';
        $rate = $exchange_rates['rate'] ?? 1;

        if ($rate != 1) {
            $converted_price = round(($data['price'] * $rate) / 100) * 100;
        }

        if ($exchange_rates['symbol_prefix']) {
            $formatted_price .= $exchange_rates['symbol'];

            if ($exchange_rates['symbol_space']) {
                $formatted_price .= ' ';
            }
        }

        $formatted_price .= number_format(
            $converted_price ?? $data['price'],
            0,
            $exchange_rates['decimal_separator'],
            $exchange_rates['thousand_separator'],
        );

        if (!$exchange_rates['symbol_prefix']) {
            if ($exchange_rates['symbol_space']) {
                $formatted_price .= ' ';
            }

            $formatted_price .= $exchange_rates['symbol'];
        }

        return $formatted_price;
    }

    public static function get_currency_data($from_currency, $to_currency)
    {
        $from_currency = strtoupper($from_currency);
        $to_currency = strtoupper($to_currency);

        $result = Estatebud::instance()
            ->cache(Cache::TTL_1D)
            ->get_currency_rates([
                'base' => $from_currency,
                'symbols' => $to_currency,
                'amount' => 1,
            ]);
        
        $currency_data = [
            'base_currency' => [
                'currency' => $from_currency,
                'symbol' => $result['details']['symbol'],
                'symbol_prefix' => (bool) $result['details']['symbol_prefix'],
                'symbol_space' => (bool) $result['details']['symbol_space'],
                'thousand_separator' => $result['details']['thousand_separator'],
                'decimal_separator' => $result['details']['decimal_separator'] ?: '.',
            ],
            'exchange_rates' => [
                'currency' => $to_currency,
                'rate' => (float) $result['rates'][$to_currency],
                'symbol' => $result['exchange_rates'][$to_currency]['details']['symbol'],
                'symbol_prefix' => (bool) $result['exchange_rates'][$to_currency]['details']['symbol_prefix'],
                'symbol_space' => (bool) $result['exchange_rates'][$to_currency]['details']['symbol_space'],
                'thousand_separator' => $result['exchange_rates'][$to_currency]['details']['thousand_separator'],
                'decimal_separator' => $result['exchange_rates'][$to_currency]['details']['decimal_separator'] ?: '.',
            ]
        ];

        return $currency_data;
    }

    public static function unique_id($prefix, $length = 12)
    {
        return $prefix . substr(md5(openssl_random_pseudo_bytes(20)), -$length);
    }

    public static function slugify($str, $delimiter = '-', $transliterate = true, $max_length = 100)
    {
        $str = mb_convert_encoding((string)$str, 'UTF-8', mb_list_encodings());
        
        $char_map = [
            // Latin
            'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C', 
            'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 
            'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O', 
            'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH', 
            'ß' => 'ss', 
            'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c', 
            'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 
            'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o', 
            'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th', 
            'ÿ' => 'y',

            // Latin symbols
            '©' => '(c)',

            // Greek
            'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
            'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
            'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
            'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
            'Ϋ' => 'Y',
            'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
            'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
            'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
            'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
            'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',

            // Turkish
            'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
            'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g', 

            // Russian
            'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
            'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
            'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
            'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
            'Я' => 'Ya',
            'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
            'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
            'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
            'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
            'я' => 'ya',

            // Ukrainian
            'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
            'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',

            // Czech
            'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U', 
            'Ž' => 'Z', 
            'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
            'ž' => 'z', 

            // Polish
            'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z', 
            'Ż' => 'Z', 
            'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
            'ż' => 'z',

            // Latvian
            'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N', 
            'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
            'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
            'š' => 's', 'ū' => 'u', 'ž' => 'z'
        ];
        
        if ($transliterate) {
            $str = str_replace(array_keys($char_map), $char_map, $str);
        }

        $replacements = [
            '.' => ''
        ];
        
        $str = str_replace(array_keys($replacements), $replacements, $str);
        $str = preg_replace('/[^\p{L}\p{Nd}]+/u', $delimiter, $str);
        $str = preg_replace('/(' . preg_quote($delimiter, '/') . '){2,}/', '$1', $str);
        $str = mb_substr($str, 0, $max_length, 'UTF-8');
        $str = trim($str, $delimiter);

        return mb_strtolower($str, 'UTF-8');
    }
}
