<?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\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 = [])
    {
        if (str_contains($url, plugins_url())) {
            return $url;
        }

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

    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(($amount * $ratio) / $supportedUnits['km']) . ' km';
        }

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

    public static function get_locale()
    {
        $locale = explode('_', get_locale())[0];

        return $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_form_terms()
    {
        $forms_model = Forms::instance();
        $all_forms = $forms_model->get_all_forms();
        $translatable_terms = [];

        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'];
        }

        foreach ([$language, 'en'] as $_language) {
            foreach ($array as $key => $value) {
                if ($_language == $key || substr($key, 0, 2) == $_language) {
                    $term = $value;
                    break 2;
                }
            }
        }

        return $term ?? '';
    }

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

        $formatted_price = '';

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

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

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

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

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

        $formatted_price .= number_format_i18n(
            $converted_price ?? $data['price'],
            0
        );

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

            $formatted_price .= $currency_data['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 = [
            '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($string, $delimiter = '-')
    {
        $string = mb_convert_encoding($string, 'UTF-8', mb_list_encodings());
        $string = preg_replace('/[^\p{L}\p{Nd}]+/u', $delimiter, $string);
        $string = preg_replace('/(' . preg_quote($delimiter, '/') . '){2,}/', '$1', $string);
        $string = trim($string, $delimiter);

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