<?php

namespace CodeConfig\EAW\Utils;

use CodeConfig\EAW\AppSettings;

defined('ABSPATH') || exit();

class Helpers
{
    /**
     * Deactivates the plugin and displays an error message.
     *
     * This method deactivates the plugin and terminates execution with a
     * specified error message. It is typically used when plugin activation
     * fails, providing the user with a link to return to the Plugins page.
     *
     * @param string $message The error message to display to the user.
     */
    public static function deactivateAndNotify($message)
    {
        deactivate_plugins(plugin_basename(CCPEAW_FILE));
        wp_die(
            sprintf(
                '<p>%s</p><p><a href="%s">%s</a></p>',
                esc_html($message),
                esc_url(admin_url('plugins.php')),
                esc_html(__('Return to Plugins Page', "essential-addons-for-woocommerce"))
            ),
            esc_html(__('Plugin Activation Failed', "essential-addons-for-woocommerce")),
            ['back_link' => true]
        );
    }

    public static function checkPluginRequirements()
    {
        if (version_compare(get_bloginfo('version'), CCPEAW_WP_VERSION, '<')) {
            self::deactivateAndNotify('WordPress version ' . CCPEAW_WP_VERSION . ' or higher is required.');
        }

        if (version_compare(PHP_VERSION, CCPEAW_PHP_VERSION, '<')) {
            self::deactivateAndNotify('PHP version ' . CCPEAW_PHP_VERSION . ' or higher is required.');
        }
    }

    public static function getVersion()
    {
        return CCPEAW_VERSION;
    }

    public static function getPluginName()
    {
        return CCPEAW_NAME;
    }

    public static function getPluginSlug()
    {
        return CCPEAW_SLUG;
    }

    public static function getPluginFile()
    {
        return CCPEAW_FILE;
    }

    public static function getPluginPath()
    {
        return CCPEAW_PATH;
    }

    public static function getPluginUrl()
    {
        return CCPEAW_URL;
    }

    public static function getPluginTextDomain()
    {
        return 'essential-addons-for-woocommerce';
    }

    public static function getPluginTextDomainPath()
    {
        return dirname(plugin_basename(CCPEAW_FILE)) . '/languages/';
    }

    public static function getInstalledVersion()
    {
        return get_option('eaw_version');
    }

    public static function getInstallTime()
    {
        return get_option('eaw_install_time');
    }

    public static function getSettings()
    {
        $data = get_option(CCPEAW_OPTIONS_NAME, []);

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

        // Deserialize any serialized values
        $formattedData = [];
        foreach ($data as $key => $value) {
            $formattedData[$key] = is_serialized($value) ? maybe_unserialize($value) : $value;
        }

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $formattedData[$key] = $value;
            } elseif ($value === '0') {
                $formattedData[$key] = false;
            } else {
                $formattedData[$key] = is_serialized($value) ? maybe_unserialize($value) : $value;
            }
        }

        return $formattedData;
    }
    public static function getSetting($key = null, $defaultValue = null)
    {
        $settings = self::getSettings();

        return $settings[$key] ?? $defaultValue;
    }

    public static function updateSettings($data)
    {
        return update_option(CCPEAW_OPTIONS_NAME, $data);
    }

    public static function getProduct($id)
    {
        $product = wc_get_product($id);

        if (empty($product)) {
            return false;
        }

        $product = [
            'id'                => $product->get_id(),
            'title'             => $product->get_title(),
            'description'       => $product->get_description(),
            'short_description' => $product->get_short_description(),
            'image'             => $product->get_image(),
            'price'             => $product->get_price(),
            'regular_price'     => $product->get_regular_price(),
            'sale_price'        => $product->get_sale_price(),
            'type'              => $product->get_type(),
            'sku'               => $product->get_sku(),
            'stock_quantity'    => $product->get_stock_quantity(),
            'stock_status'      => $product->get_stock_status(),
            'manage_stock'      => $product->get_manage_stock(),
            'weight'            => $product->get_weight(),
            'length'            => $product->get_length(),
            'width'             => $product->get_width(),
            'height'            => $product->get_height(),
            'parent_id'         => $product->get_parent_id(),
            'permalink'         => $product->get_permalink(),
            'slug'              => $product->get_slug(),
            'status'            => $product->get_status(),
            'terms'             => $product->get_categories(),
        ];

        return $product;
    }

    public static function getSavedCart()
    {
        if (!is_user_logged_in()) {
            return [];
        }

        $user_id = get_current_user_id();
        $carts   = get_user_meta($user_id, 'ccpeaw_saved_carts', true);

        return is_array($carts) ? $carts : [];
    }

    public static function deleteSavedCart($cartId)
    {
        if (!is_user_logged_in()) {
            return false;
        }

        $user_id = get_current_user_id();
        $carts   = get_user_meta($user_id, 'ccpeaw_saved_carts', true);

        if (!is_array($carts)) {
            return false;
        }

        unset($carts[$cartId]);

        return update_user_meta($user_id, 'ccpeaw_saved_carts', $carts);
    }

    public static function setSaveCart($cartName, $cartData)
    {
        if (!is_user_logged_in()) {
            return false;
        }

        if (empty($cartName) || !is_string($cartName)) {
            return false;
        }

        if (empty($cartData) || !is_array($cartData)) {
            return false;
        }

        $user_id = get_current_user_id();

        $existingCarts = self::getSavedCart();

        $cartId = wp_generate_password(8, false);

        $newCart = [
            'id'   => $cartId,
            'name' => sanitize_text_field($cartName),
            'data' => array_map(function ($item) {
                return [
                    'product_id' => isset($item['product_id']) ? intval($item['product_id']) : 0,
                    'quantity'   => isset($item['quantity']) ? intval($item['quantity']) : 1,
                ];
            }, $cartData),
        ];

        $existingCarts[$cartId] = $newCart;

        return update_user_meta($user_id, 'ccpeaw_saved_carts', $existingCarts);
    }

    public static function restoreSavedCart($cartId)
    {

        $user_id = get_current_user_id();
        $carts   = get_user_meta($user_id, 'ccpeaw_saved_carts', true);

        if (!is_array($carts) || !isset($carts[$cartId]) || !isset($carts[$cartId]['data'])) {
            wp_send_json_error([
                'error'   => 'invalid_cart',
                'message' => __('Invalid cart ID.', "essential-addons-for-woocommerce"),
            ]);
        }

        $cartData   = $carts[$cartId]['data'];
        $addedItems = [];
        $errors     = [];

        WC()->cart->empty_cart();

        foreach ($cartData as $key => $item) {

            if (!isset($item['product_id']) || !isset($item['quantity'])) {
                $errors[] = sprintf(
                    '%s %d %s',
                    __('Item ', "essential-addons-for-woocommerce"),
                    $key + 1,
                    __('is missing required data.', "essential-addons-for-woocommerce")
                );
                continue;
            }

            $product_id = $item['product_id'];
            $quantity   = $item['quantity'];

            $cartItemKey = WC()->cart->add_to_cart($product_id, $quantity);

            if (!$cartItemKey) {
                $errors[] = sprintf(
                    '%s %d %s %d %s',
                    __('Failed to add product ID ', "essential-addons-for-woocommerce"),
                    $product_id,
                    __('(Quantity:', "essential-addons-for-woocommerce"),
                    $quantity,
                    __(') to the cart.', "essential-addons-for-woocommerce")
                );
            } else {
                $addedItems[$cartItemKey] = [
                    'product_id' => $product_id,
                    'quantity'   => $quantity,
                ];
            }
        }

        if (empty($addedItems)) {
            return;
        }

        return [
            'success'    => true,
            'message'    => __('Cart restored successfully!', "essential-addons-for-woocommerce"),
            'addedItems' => $addedItems,
        ];
    }

    public static function copySavedCart($cartId, $currentPage = null)
    {

        if (empty($cartId)) {
            wp_send_json_error(['message' => __('Invalid cart ID.', "essential-addons-for-woocommerce")], 400);
        }

        // Get the user's saved carts
        $user_id = get_current_user_id();

        $carts = get_user_meta($user_id, 'ccpeaw_saved_carts', true);

        if ($currentPage == 'cart') {
            $carts = WC()->cart->get_cart_contents();
        }

        if (empty($carts)) {
            return false;
        }

        $cartData = array_map(function ($item) {
            return [
                'product_id' => isset($item['product_id']) ? intval($item['product_id']) : 0,
                'quantity'   => isset($item['quantity']) ? intval($item['quantity']) : 1,
            ];
        }, array_values($carts));

        $shareUrl = self::generateSharedCartLink($cartData);

        return $shareUrl;
    }

    public static function shareCartOnSocial($currentPage, $network = 'facebook')
    {
        // Validate the current page
        if ($currentPage !== 'cart') {
            return false; // Only allow sharing from the cart page
        }

        // Get the cart contents
        $carts = WC()->cart ? WC()->cart->get_cart_contents() : [];

        if (empty($carts)) {
            return false; // Exit if the cart is empty
        }

        // Map cart data into a simplified structure
        $cartData = array_map(function ($item) {
            return [
                'product_id' => isset($item['product_id']) ? intval($item['product_id']) : 0,
                'quantity'   => isset($item['quantity']) ? intval($item['quantity']) : 1,
            ];
        }, array_values($carts));

        $generatedURL      = self::generateSharedCartLink($cartData);
        $shareUrlOnNetwork = self::getSocialShareUrl($network, $generatedURL);

        return [
            'url' => $shareUrlOnNetwork
        ];
    }

    private static function getSocialShareUrl($network, $url)
    {
        $encodedUrl = rawurlencode($url);
        $text       = rawurlencode(__('Check out my cart on WooCommerce!', 'essential-addons-for-woocommerce'));
        $siteName   = rawurlencode(get_bloginfo('name'));

        switch ($network) {
            case 'facebook':
                return 'https://www.facebook.com/sharer/sharer.php?u=' . $encodedUrl;
            case 'x':
                $tweetText = substr($text, 0, 280 - strlen($encodedUrl) - 10);

                return 'https://twitter.com/intent/tweet?text=' . $tweetText . '&url=' . $encodedUrl;
            case 'linkedin':
                return 'https://www.linkedin.com/shareArticle?mini=true&url=' . $encodedUrl . '&title=' . $text . '&source=' . $siteName;
            case 'whatsapp':
                return 'https://api.whatsapp.com/send?text=' . $text . '%20' . $encodedUrl;
            case 'email':
                return 'mailto:?subject=' . rawurlencode(__('Check out my cart', 'essential-addons-for-woocommerce')) .
                    '&body=' . $text . '%20' . $encodedUrl;
            default:
                return '#';
        }
    }

    public static function generateSharedCartLink($cartData)
    {
        if (empty($cartData) || !is_array($cartData)) {
            return '#';
        }

        $encodedCartData = base64_encode(wp_json_encode($cartData));

        $shareUrl = add_query_arg('shared_cart', $encodedCartData, site_url());

        return $shareUrl;
    }

    public static function getAllProducts()
    {
        $args = [
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => -1
        ];

        $products = get_posts($args);

        if (empty($products)) {
            return false;
        }

        $products = array_map(function ($product) {
            return [
                'value' => $product->ID,
                'label' => $product->post_title
            ];
        }, $products);

        return $products;
    }

    public static function getAllProductsByTitle($title)
    {
        // Create cache key based on search title
        $cache_key = 'ccpeaw_products_by_title_' . md5($title);
        $cached    = wp_cache_get($cache_key, 'ccpeaw_products');

        if (false !== $cached) {
            return $cached;
        }

        global $wpdb;

        $query = $wpdb->prepare("
            SELECT ID, post_title 
            FROM {$wpdb->posts} 
            WHERE post_type = 'product' 
            AND post_status = 'publish' 
            AND post_title LIKE %s
            ORDER BY post_title ASC
        ", '%' . $wpdb->esc_like($title) . '%');

        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        $results = $wpdb->get_results($query);
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared

        $results = is_array($results) ? $results : [];

        // Cache results for 1 hour
        wp_cache_set($cache_key, $results, 'ccpeaw_products', HOUR_IN_SECONDS);

        return $results;
    }

    public static function setWishlist($productId)
    {
        $user_id    = get_current_user_id();
        $wishlist   = get_user_meta($user_id, 'ccpeaw_wishlist', true);
        $wishlist   = is_array($wishlist) ? $wishlist : [];
        $wishlist[] = $productId;
        $wishlist   = array_unique($wishlist);
        update_user_meta($user_id, 'ccpeaw_wishlist', $wishlist);

        return $wishlist;
    }

    public static function getWishlist()
    {
        $user_id  = get_current_user_id();
        $wishlist = get_user_meta($user_id, 'ccpeaw_wishlist', true);

        return $wishlist;
    }

    public static function getAllCategories()
    {
        $args = [
            'taxonomy'   => 'product_cat',
            'hide_empty' => false,
        ];

        $categories = get_terms($args);

        if (is_wp_error($categories) || empty($categories)) {
            return false;
        }

        $result = [];

        foreach ($categories as $category) {
            $result[] = [
                'id'    => $category->term_id,
                'label' => $category->name,
            ];
        }

        return $result;
    }

    public static function getCategory($category_id)
    {
        $category = get_term($category_id, 'product_cat');

        return $category;
    }

    public static function setToCart($productId, $quantity)
    {
        WC()->cart->add_to_cart($productId, $quantity);
        $cart = WC()->cart->get_cart();

        return $cart;
    }

    public static function getTabs()
    {
        function tabs($tabs)
        {
            return $tabs;
        }
    }

    // get all available user roles
    public static function getRoles()
    {
        $roles = get_editable_roles();

        $rolesData = array_map(
            function ($role_name, $role_data) {
                return [
                    'label' => $role_data['name'],
                    'value' => $role_name,
                ];
            },
            array_keys($roles),
            $roles
        );

        return $rolesData;
    }

    // get all product categories
    public static function getCategories()
    {
        $categories = get_categories([
            'hide_empty' => false,
            'taxonomy'   => 'product_cat'
        ]);

        $categoriesData = array_map(
            function ($category) {
                return [
                    'label' => $category->name,
                    'value' => $category->term_id,
                ];
            },
            $categories
        );

        return $categoriesData;
    }

    // get products variations from product id
    public static function getVariationByProductId($productId, $variationSelection = null)
    {
        $product = wc_get_product($productId);

        if (!$product || $product->get_type() !== 'variable') {
            return [];
        }

        $_variations = [];

        foreach ($variationSelection as $key => $value) {
            $_key               = str_replace('attribute_', '', $key);
            $_variations[$_key] = $value;
        }

        $variationsChildren = $product->get_children();

        $variations = [];

        foreach ($variationsChildren as $key => $variation_id) {
            $variation = wc_get_product($variation_id);

            if (!empty($_variations)) {
                $array2 = $variation->get_attributes();

                $is_eq = empty(array_diff($_variations, $array2)) && empty(array_diff($array2, $_variations));

                if (!$is_eq) {
                    continue;
                }
            }

            $variations[] = [
                'id'      => $variation_id,
                'name'    => $variation->get_name(),
                'attr'    => $variation->get_attributes(),
                'sku'     => $variation->get_sku(),
                'price'   => $variation->get_price(),
                'regular' => $variation->get_regular_price(),
                'sale'    => $variation->get_sale_price(),
                'image'   => $variation->get_image(),
                'status'  => $variation->get_status(),
            ];
        }

        return $variations;
    }

    public static function getProductVariations()
    {
        $variations = wc_get_products([
            'type'           => 'variation',
            'posts_per_page' => -1
        ]);

        $variationsData = array_map(
            function ($variation) {
                return [
                    'value'      => $variation->get_id(),
                    'label'      => $variation->get_name(),
                ];
            },
            $variations
        );

        return $variationsData;
    }

    public static function getSelectedVariationImg($variationSelection, $product_id)
    {
        $variations = self::getVariationByProductId($product_id, $variationSelection);

        $attachmentId = get_post_thumbnail_id($variations[0]['id']);

        $imageSrc = wp_get_attachment_image_src($attachmentId, 'full');

        if (!empty($variations)) {
            return [
                'id'            => $variations[0]['id'],
                'attachment_id' => $attachmentId,
                'src'           => $imageSrc[0],
                'url'           => $variations[0]['image'],
            ];
        }

        return false;
    }

    public static function getProductSkus()
    {
        $products = wc_get_products([
            'type'  => 'simple',
            'limit' => -1,
        ]);

        return array_map(function ($product) {
            $sku = $product->get_sku();

            return [
                'label' => $sku,
                'value' => $sku,
            ];
        }, $products);
    }

    /**
     * Get all product attributes with terms.
     */
    public static function getProductAttributes()
    {
        $attributes = wc_get_attribute_taxonomies();

        if (empty($attributes) || !is_array($attributes)) {
            return [];
        }

        return array_map(function ($attribute) {
            $taxonomy = wc_attribute_taxonomy_name($attribute->attribute_name);
            $terms    = [];

            if (taxonomy_exists($taxonomy)) {
                $term_objects = get_terms([
                    'taxonomy'   => $taxonomy,
                    'hide_empty' => false,
                ]);

                if (!is_wp_error($term_objects) && is_array($term_objects)) {
                    $terms = array_map(function ($term) use ($taxonomy) {
                        return [
                            'id'             => $term->term_id,
                            'name'           => $term->name,
                            'slug'           => $term->slug,
                            'eaw_term_value' => get_term_meta($term->term_id, 'product_' . $taxonomy, true),
                        ];
                    }, $term_objects);
                }
            }

            return [
                'id'              => $attribute->attribute_id,
                'label'           => $attribute->attribute_label,
                'showInVariation' => (bool) $attribute->attribute_public,
                'showInProduct'   => (bool) $attribute->attribute_public,
                'type'            => $attribute->attribute_type,
                'value'           => $attribute->attribute_name,
                'terms'           => $terms,
            ];
        }, $attributes);
    }

    /**
     * Add a new product attribute.
     */
    public static function addProductAttribute($attrName, $attrType, $attrTerms, $showInProduct = true, $showInVariation = false)
    {
        global $wpdb;

        // Check if attribute already exists
        $attribute_id = wc_attribute_taxonomy_id_by_name($attrName);

        if ($attribute_id) {
            // Update existing attribute
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update(
                $wpdb->prefix . 'woocommerce_attribute_taxonomies',
                [
                    'attribute_label'   => $attrName,
                    'attribute_type'    => $attrType,
                    'attribute_orderby' => 'menu_order',
                    'attribute_public'  => (int) $showInProduct,
                ],
                ['attribute_id' => $attribute_id]
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

            // Ensure attribute updates are applied and clear cache
            delete_transient('wc_attribute_taxonomies');
            wp_cache_delete('wc_attribute_taxonomies', 'woocommerce');
        } else {
            // Create new attribute
            $attribute_id = wc_create_attribute([
                'name'         => $attrName,
                'type'         => $attrType,
                'is_taxonomy'  => true,
                'is_visible'   => (bool) $showInProduct,
                'is_variation' => (bool) $showInVariation,
                'is_required'  => true,
            ]);

            if (is_wp_error($attribute_id)) {
                return $attribute_id;
            }

            delete_transient('wc_attribute_taxonomies');
            flush_rewrite_rules();

            // Register taxonomy only for new attributes
            $taxonomy = wc_attribute_taxonomy_name($attrName);
            register_taxonomy($taxonomy, 'product', [
                'hierarchical' => true,
                'show_ui'      => true,
                'query_var'    => true,
                'rewrite'      => false,
            ]);
        }

        // Get existing terms
        $taxonomy      = wc_attribute_taxonomy_name($attrName);
        $existingTerms = get_terms([
            'taxonomy'   => $taxonomy,
            'hide_empty' => false,
            'fields'     => 'id=>name',
        ]);

        $existingTermNames = array_flip($existingTerms); // Flip for name-to-ID lookup
        $inputTermNames    = [];

        // Add or update terms
        foreach ($attrTerms as $termData) {
            if (is_array($termData) && isset($termData['name'])) {
                $termName    = sanitize_text_field($termData['name']);
                $customValue = sanitize_text_field($termData['eaw_term_value'] ?? '');

                $inputTermNames[] = $termName;

                if (isset($existingTermNames[$termName])) {
                    // Term exists, update custom value
                    update_term_meta($existingTermNames[$termName], 'product_' . $taxonomy, $customValue);
                } else {
                    // Term doesn't exist, create it
                    $newTerm = wp_insert_term($termName, $taxonomy, ['slug' => sanitize_title($termName)]);
                    if (!is_wp_error($newTerm) && isset($newTerm['term_id'])) {
                        update_term_meta($newTerm['term_id'], 'product_' . $taxonomy, $customValue);
                    }
                }
            }
        }

        // Remove terms not in the input
        foreach ($existingTerms as $termID => $termName) {
            if (!in_array($termName, $inputTermNames, true)) {
                wp_delete_term($termID, $taxonomy);
            }
        }

        return [
            'success' => true,
            'message' => $attribute_id ? __('Attribute updated successfully.', 'essential-addons-for-woocommerce') : __('Attribute created successfully.', 'essential-addons-for-woocommerce'),
        ];
    }


    /**
     * Delete a product attribute.
     */
    public static function deleteProductAttribute($attrName)
    {
        // Get the attribute ID by its name
        $attribute_id = wc_attribute_taxonomy_id_by_name($attrName);
        if (!$attribute_id) {
            return new \WP_Error('invalid_attribute', __('Attribute not found.', 'essential-addons-for-woocommerce'));
        }

        // Get the taxonomy name associated with the attribute
        $taxonomy = wc_attribute_taxonomy_name($attrName);

        // If the taxonomy exists, delete its terms and custom term values
        if (taxonomy_exists($taxonomy)) {
            // Get all terms associated with the taxonomy
            $terms = get_terms([
                'taxonomy'   => $taxonomy,
                'hide_empty' => false,
            ]);

            if (!is_wp_error($terms)) {
                foreach ($terms as $term) {
                    // Delete custom values for the term
                    delete_term_meta($term->term_id, 'eaw_term_value');

                    // Delete the term itself
                    wp_delete_term($term->term_id, $taxonomy);
                }
            }

            // Unregister the taxonomy
            unregister_taxonomy($taxonomy);
        }

        // Delete the WooCommerce attribute itself
        $deleted = wc_delete_attribute($attribute_id);

        if (is_wp_error($deleted)) {
            return new \WP_Error('attribute_deletion_failed', __('Failed to delete attribute.', 'essential-addons-for-woocommerce'));
        }

        // Delete custom values for the attribute (stored in wp_options or elsewhere)
        delete_option('eaw_attr_type_' . $attribute_id);

        return [
            'success' => true,
            'message' => __('Attribute and its associated data deleted successfully.', 'essential-addons-for-woocommerce'),
        ];
    }
    public static function arrayMapRecursive($callback, $array)
    {
        $func = function ($item) use (&$func, $callback) {
            return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
        };

        return array_map($func, $array);
    }

    private static function sanitize_nested_array($data)
    {
        $sanitize_data = [];

        foreach ($data as $key => $value) {
            if (is_string($value)) {
                $sanitize_data[$key] = sanitize_text_field($value);
            } elseif (is_array($value)) {
                $sanitize_data[$key] = self::sanitize_nested_array($value);
            }
        }

        return $sanitize_data;
    }

    public static function sanitization($data)
    {
        $sanitize_data = '';

        if (is_array($data)) {

            $sanitize_data = self::sanitize_nested_array($data);
        } elseif (is_string($data)) {

            $sanitize_data = sanitize_text_field($data);
        }

        return $sanitize_data;
    }

    public static function getLanguageInfo()
    {
        $default_language = '';
        $languages        = [];
        $languages_data   = [];

        if (is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
            /*wpml*/
            global $sitepress;
            $default_language       = $sitepress->getDefault_language();
            $languages              = icl_get_languages('skip_missing=N&orderby=KEY&order=DIR&link_empty_to=str');
            $languages_data         = $languages;
            if (count($languages)) {
                foreach ($languages as $key => $language) {
                    if ($key != $default_language) {
                        $languages[] = $key;
                    }
                }
            }
        } elseif (class_exists('Polylang')) {
            $languages         = function_exists('pll_languages_list') ? pll_languages_list() : [];
            $default_language  = function_exists('pll_default_language') ? pll_default_language('slug') : '';
            foreach ($languages as $language) {
                if ($language == $default_language) {
                    continue;
                }
                $languages[] = $language;
            }
        }

        return [
            'default_language' => $default_language,
            'languages'        => $languages,
            'languages_data'   => $languages_data
        ];
    }
    public static function eawSanitizeFields($data)
    {
        if (is_array($data)) {
            return array_map([__CLASS__, 'eawSanitizeFields'], $data);
        } else {
            return is_scalar($data) ? sanitize_text_field(wp_unslash($data)) : $data;
        }
    }

    public static function getMenus()
    {
        $menus = get_terms([
            'taxonomy'   => 'nav_menu',
            'hide_empty' => false,
        ]);

        if (!empty($menus) && !is_wp_error($menus)) {
            return array_map(function ($menu) {
                return [
                    'value'     => $menu->slug,
                    'label'     => $menu->name,
                ];
            }, $menus);
        }

        return [];
    }

    /**
     * Sanitize multi-select values
     *
     * @param array $values The input values
     * @param WP_Customize_Setting $setting The setting object
     * @return array Sanitized array of values
     */
    public static function sanitize_multi_select($values, $setting)
    {
        if (!is_array($values)) {
            return [];
        }

        // Get valid choices from the setting's control
        $valid_choices = $setting->manager->get_control($setting->id)->choices;
        $sanitized     = [];

        foreach ($values as $value) {
            if (array_key_exists($value, $valid_choices)) {
                $sanitized[] = sanitize_text_field($value);
            }
        }

        return $sanitized;
    }

    /**
     * Get available WordPress navigation menus for Customizer choices
     *
     * @return array Associative array of menu slug => menu name
     */
    public static function getCustomizerMenus()
    {
        $menus = get_terms([
            'taxonomy'   => 'nav_menu',
            'hide_empty' => false,
        ]);

        $menu_choices = [];

        if (!empty($menus) && !is_wp_error($menus)) {
            foreach ($menus as $menu) {
                $menu_choices[$menu->slug] = $menu->name;
            }
        }

        return $menu_choices;
    }

    public static function getViewedProducts(int $currentProductId): array
    {
        $viewedProducts = isset($_COOKIE['ccpeaw_recently_viewed']) ? sanitize_text_field(wp_unslash($_COOKIE['ccpeaw_recently_viewed'])) : '';

        if (empty($viewedProducts)) {
            return [];
        }

        $products = array_filter(
            array_map('intval', explode('|', $viewedProducts)),
            fn ($id) => $id !== $currentProductId && $id > 0
        );

        return array_unique($products, SORT_NUMERIC);
    }


    public static function deleteViewedProducts(int $currentProductId): void
    {
        $viewedProducts = isset($_COOKIE['ccpeaw_recently_viewed']) ? sanitize_text_field(wp_unslash($_COOKIE['ccpeaw_recently_viewed'])) : '';

        if (empty($viewedProducts)) {
            return;
        }

        $products = array_filter(
            array_map('intval', explode('|', wp_unslash($viewedProducts))),
            fn ($id) => $id > 0 && $id !== $currentProductId
        );

        // Reset the cookie with remaining product IDs
        setcookie('ccpeaw_recently_viewed', implode('|', $products), time() + 30 * DAY_IN_SECONDS, '/');
    }

    public static function getCurrency($currency)
    {
        return self::convert_currency(1, $currency);
    }

    private static function fetch_exchange_rate($from, $to)
    {
        $cache_key = "exchange_rate_{$from}_{$to}";
        $cached    = get_transient($cache_key);

        $api = AppSettings::getInstance()->getParams('converterApi');

        if ($cached !== false) {
            return (float) $cached;
        }

        $api_url  = sprintf('https://v6.exchangerate-api.com/v6/%s/latest/%s', $api, $from);
        $response = wp_remote_get($api_url);

        if (is_wp_error($response)) {
            return 1.0; // fallback to default rate
        }

        $data = json_decode(wp_remote_retrieve_body($response), true);
        $rate = $data['conversion_rates'][$to] ?? 1.0;

        set_transient($cache_key, $rate, HOUR_IN_SECONDS * 12);

        return (float) $rate;
    }

    private static function convert_currency($price, $currency)
    {
        $base_currency = get_option('woocommerce_currency', 'USD');
        $rate          = self::fetch_exchange_rate($base_currency, $currency);
        $price         = is_numeric($price) ? (float) $price : 0.0;

        return $price * $rate;
    }
}
