<?php
if (!defined('ABSPATH')) {exit;}
/* phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange */

if (!function_exists('WP_Filesystem')) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
}

include_once('src/'.KRFSAPP_THEME.'/theme-functions.php');

function krfsapp_getMeta($key) {
    global $wpdb;
    $result = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}krfs_metadata WHERE meta_key = %s",
            $key
        ),
        ARRAY_A
    );
    if (count($result) > 0) {
        return $result[0]['meta_value'];
    }
    return false;
}

function krfsapp_file_put_contents($file, $data) {
    if (WP_Filesystem()) {
        global $wp_filesystem;
        $wp_filesystem->put_contents($file, $data, FS_CHMOD_FILE);
    }
}

function krfsapp_get_post_id_by_slug($slug) {
    $query = new WP_Query(
        array(
            'name' => $slug,
            'post_type' => 'page',
            'numberposts' => 1,
            'fields' => 'ids',
        )
    );
    $posts = $query->get_posts();
    return array_shift($posts);
}

function krfsapp_update_page_status($slug, $status) {
    $new_status = $status ? 'publish' : 'draft';

    $page_id = krfsapp_get_post_id_by_slug($slug);

    $updated_page = array(
        'ID' => $page_id,
        'post_status' => $new_status,
    );
    $result = wp_update_post($updated_page);
    if ($result) {
        return $page_id;
    } else {
        return false;
    }
}
function krfsapp_create_pages($title, $content, $slug, $status) {
    $new_status = $status ? 'publish' : 'draft';
    if (krfsapp_get_post_id_by_slug($slug) == false) {
        $page = array(
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => $new_status,
            'post_type' => 'page'
        );

        if ($slug) {
            $page['post_name'] = $slug;
        }
        $page_id = wp_insert_post($page);

        if ($page_id) {
            return $page_id;
        } else {
            return false;
        }
    } else {
        return krfsapp_update_page_status($slug, $status);
    }
}


// remove_filter('sanitize_title', 'sanitize_title_with_dashes');

function krfsapp_addMeta($key, $value) {
    global $wpdb;
    // Check if the key already exists
    $existing_meta = krfsapp_getMeta($key);
    if (is_bool($existing_meta) && $existing_meta === false) {
        $wpdb->insert($wpdb->prefix . 'krfs_metadata', array('meta_key' => $key, 'meta_value' => $value), array('%s', '%s'));
    } else {
        $wpdb->update($wpdb->prefix . 'krfs_metadata', array('meta_value' => $value), array('meta_key' => $key), array('%s'), array('%s'));
    }
}

function krfsapp_file_get_contents($path) {
    $reponse = wp_remote_get($path);
    if (is_wp_error($reponse)) {
        return false;
    } else {
        return wp_remote_retrieve_body($reponse);
    }
}

function krfsapp_gen_uuidv4() {
    $data = random_bytes(16);

    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
        
    return vsprintf('%s%s%s%s%s%s%s%s', str_split(bin2hex($data), 4));
}

function krfsapp_slugExists($array, $slug) {
    foreach ($array as $item) {
        if (isset($item['slug']) && $item['slug'] === $slug) {
            return true;
        }
    }
    return false;
}

function krfsapp_set_completed_tab($tab, $bool) {
    global $krfsapp_active_tab_config;
    if($krfsapp_active_tab_config) {
        // $krfsapp_active_tab_config[$tab]['completed'] = $bool;
    }
    $temp_krfs_active_tab_config = json_decode(krfsapp_getMeta('_admin_tab_config'), true);
    $temp_krfs_active_tab_config[$tab]['completed'] = $bool;
    krfsapp_addMeta('_admin_tab_config', wp_json_encode($temp_krfs_active_tab_config));
    unset($temp_krfs_active_tab_config); // Free memory
}

function krfsapp_page_exists($page_id) {
    $page = get_post($page_id);
    return $page ? true : false;
}

function krfsapp_getPageUrlById($page_id) {
    $page_slug = get_post_field('post_name', $page_id);
    return site_url() . '/' . $page_slug . '/';
}

function krfsapp_get_string($group, $key) {
    $user_defined_localization = krfsapp_file_get_contents(KRFSAPP_PLUGIN_DIR . '/languages/user-defined-localization.json');
    $lang = krfsapp_determine_locale();
    if($user_defined_localization) {
        $user_defined_localization = json_decode($user_defined_localization, true);
        if(isset($user_defined_localization[$group]) && isset($user_defined_localization[$group][$key])) {
            return $user_defined_localization[$group][$key][$lang];
        }
    }
    return "";
}

function krfsapp_format_price($price) {
    $locale = determine_locale();
    $currencyCode = get_woocommerce_currency();
    $formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
    $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
    $formattedCurrency = $formatter->formatCurrency(intval($price), $currencyCode);
    $cleanedCurrency = preg_replace('/[A-Za-z]+(?=\$)/', '', $formattedCurrency);
    return $cleanedCurrency;
}

function krfsapp_determine_locale() {
    $locale = determine_locale();
    if($locale == "en_AU") {
        $locale = "en_GB";
    }
    $supported_langs = array('en_US', 'en_GB', 'fr_FR', 'de_DE', 'es_ES', 'it_IT');
    if(!in_array($locale, $supported_langs)) {
        $locale = $supported_langs[0];
    }
    return $locale;
}

function krfsapp_fetch_products_by_attributes($filters, $category_slug, $paged) {

    $products_per_page_setting = intval(krfsapp_getMeta('_setting_products_per_page'));

    // Initialize query arguments
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => $products_per_page_setting, // Limit number of products per page
        'paged' => $paged, // Current page
        'post_status' => 'publish', // Only published products
        'meta_query' => array(
            'relation' => 'AND',
        ),
        'tax_query' => array(
            'relation' => 'AND',
        ),
    );

    // Add price filter if specified
    if (isset($filters['minprice']) && isset($filters['maxprice'])) {
        $args['meta_query'][] = array(
            'key' => '_price',
            'value' => array(floatval($filters['minprice']), floatval($filters['maxprice'])),
            'compare' => 'BETWEEN',
            'type' => 'NUMERIC',
        );
    }

    // Filter by attributes
    if (!empty($filters['shape'])) {
        $args['tax_query'][] = array(
            'taxonomy' => 'pa_krfs_shape_attr',
            'field' => 'slug',
            'terms' => sanitize_text_field($filters['shape']),
        );
    }

    if (!empty($filters['stone'])) {
        $args['tax_query'][] = array(
            'taxonomy' => 'pa_krfs_stone_attr',
            'field' => 'slug',
            'terms' => sanitize_text_field($filters['stone']),
        );
    }

    if (!empty($filters['style'])) {
        $args['tax_query'][] = array(
            'taxonomy' => $filters['style_taxonomy'],
            'field' => 'slug',
            'terms' => (array) $filters['style'],
        );
    }

    if (!empty($filters['metal'])) {
        $selected_metals = (array) $filters['metal']; // Ensure it's treated as an array

        //  First fetch matching terms (metal_name_14k/metal_name_18k), then pass their slugs to tax_query
        $matching_terms = get_terms([
            'taxonomy'   => 'pa_krfs_metal_attr',
            'hide_empty' => false,
        ]);
        
        // $filtered_slugs = array_filter(array_map(function($term) use ($filters) {
        //     return (strpos($term->slug, sanitize_text_field($filters['metal'])) === 0) ? $term->slug : null;
        // }, $matching_terms));

        // Collect slugs that match any of the selected metals
        $filtered_slugs = array_filter(array_map(function($term) use ($selected_metals) {
            foreach ($selected_metals as $metal) {
                $metal = sanitize_text_field($metal);
                if (strpos($term->slug, $metal) === 0) {
                    return $term->slug;
                }
            }
            return null;
        }, $matching_terms));


        // $args['tax_query'][] = array(
        //     'taxonomy' => 'pa_krfs_metal_attr',
        //     'field' => 'slug',
        //     'terms'    => $filtered_slugs,
        // );

        if (!empty($filtered_slugs)) {
            $args['tax_query'][] = array(
                'taxonomy' => 'pa_krfs_metal_attr',
                'field'    => 'slug',
                'terms'    => array_values($filtered_slugs),
            );
        }
    }

    // Filter by category (if specified)
    if (!empty($category_slug)) {
        $args['tax_query'][] = array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => sanitize_text_field($category_slug),
        );
    }

    // Add search filter if specified
    if (!empty($filters['search'])) {
        $search_term = sanitize_text_field($filters['search']);
        // Custom search filter to match product title
        // Search in title and SKU
        $args['s'] = $search_term;
        
    }


    // Add result set type if specified
    if (!empty($filters['home_preview']) && $filters['home_preview'] == 'true') {
        $args['tax_query'][] = array(
            'taxonomy' => 'pa_krfs_miscs_attr',
            'field' => 'slug',
            'terms' => 'home_preview',
        );
    }


    $sort_by = $filters['sort'];
    // Sorting logic based on $sort_by
    if (isset($sort_by) && !empty($sort_by)) {
        switch ($sort_by) {
            case 'Orderbyupdatedate-desc':
                $args['orderby'] = 'modified'; // Sort by the last modified date
                $args['order'] = 'DESC'; // Descending order
                break;
            case 'Orderbydate-desc':
                $args['orderby'] = 'date'; // Sort by the published date
                $args['order'] = 'DESC'; // Descending order
                break;
            case 'Orderbyprice-asc':
                $args['meta_key'] = '_price'; // Sort by price
                $args['orderby'] = 'meta_value_num'; // Treat price as a numeric value
                $args['order'] = 'ASC'; // Ascending order
                break;
            case 'Orderbyprice-desc':
                $args['meta_key'] = '_price'; // Sort by price
                $args['orderby'] = 'meta_value_num'; // Treat price as a numeric value
                $args['order'] = 'DESC'; // Descending order
                break;
        }
    }
     $allResultArgs = $args;
     $bridal_args = $args;
    // Add result set type if specified
    if (!empty($filters['result_set']) && $filters['result_set'] == 'bridal_sets') {
        $args['tax_query'][] = array(
            'taxonomy' => 'pa_krfs_miscs_attr',
            'field' => 'slug',
            'terms' => 'bridal_sets',
        );
    }
    
    // Execute the product query
    $query = new WP_Query($args);

    // Initialize an array to store product data and pagination info
    $products_data = array(
        'products' => array(),
        'pagination' => array(),
    );
    // Check if products are found
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            global $product;

            // Gather the product data
            $product_id = $product->get_id();
            $product_data = array(
                'id' => $product_id,
                'title' => get_the_title(),
                'price' => '', // Will be updated later based on variations
                'image' => wp_get_attachment_url($product->get_image_id()),
                'link' => get_permalink(),
                'variations' => array(), // Initialize variations array
            );

            // Fetch variations for this product
            $variations = get_posts(array(
                'post_type' => 'product_variation',
                'posts_per_page' =>  $products_per_page_setting,
                'post_parent' => $product_id,
                'post_status' => 'publish',
            ));
           
            $min_price = PHP_INT_MAX; // Initialize minimum price with a large value

            $min_price = PHP_FLOAT_MAX; // Initialize min price to a very high value
            foreach ($variations as $variation) {
                $variation_product = wc_get_product($variation->ID);
                $variation_price = floatval($variation_product->get_price());
            
                // Skip variations with a price of 0
                if ($variation_price > 0 && $variation_price >= $filters['minprice'] && $variation_price <= $filters['maxprice']) {
                    $product_data['variations'][] = array(
                        'id' => $variation->ID,
                        'title' => $variation_product->get_name(),
                        'price' => $variation_price,
                    );
            
                    // Update the minimum price if the current variation price is lower
                    if ($variation_price < $min_price) {
                        $min_price = $variation_price;
                    }
                    
                }
            }
            
            // If no valid variations found, set $min_price to a default value
            if ($min_price === PHP_FLOAT_MAX) {
                $min_price = null; // Or you can set a fallback value like $filters['minprice']
            }
            
            // Update product price with the minimum variation price found
            if (isset($min_price) && $min_price < PHP_INT_MAX) {
                $product_data['price'] = $min_price;
            } else {
                // If no variations met the filter criteria, you may choose to keep the original price or set it to a default value
                $product_data['price'] = $product->get_price();
            }

            $products_data['products'][] = $product_data;
        }
        // Count products with pa_misc_attr = bridal_sets
        if($filters['result_set'] != 'bridal_sets') {
            $bridal_args['tax_query'][] = array(
                'taxonomy' => 'pa_krfs_miscs_attr',
                'field' => 'slug',
                'terms' => 'bridal_sets',
            );
            $bridal_query = new WP_Query($bridal_args);
            $bridal_sets_count = $bridal_query->found_posts;
            $all_result_query = $query->found_posts;
        }else{
            $all_result_query = new WP_Query($allResultArgs);
            $all_result_query = $all_result_query->found_posts;
            $bridal_sets_count = $query->found_posts;
        }

        // Pagination data
        $products_data['pagination'] = array(
            'current_page' => $paged,
            'total_pages' => $query->max_num_pages,
            'total_products' => $all_result_query,
            'bridal_sets_count' => $bridal_sets_count
        );
    }

    // Restore original Post Data
    wp_reset_postdata();
    return $products_data;
}

function krfsapp_prepare_ring_listing($filters_data, $category_slug, $pagination, $filters) {
    // Create an associative array mapping product IDs to their prices
    $product_prices = array();
   
    if (isset($filters_data) && is_array($filters_data)) {
        foreach ($filters_data as $filter) {
            if (isset($filter['id']) && isset($filter['price'])) {
                // Map product ID to price
                $product_prices[intval($filter['id'])] = $filter['price'];
            }
        }
    }

    // Extract the list of product IDs
    $product_ids = array_keys($product_prices);

    // If no product IDs are provided, return a message indicating no products found
    if (empty($product_ids)) {
        $Noproductsfound = esc_html('No Results Found. Please contact us to discuss customization, as all our rings are made to order.');
        return array('html' => '<p class="text-noresults-found">' . $Noproductsfound . '</p>', 'count' => 0);
    }

    $products_per_page_setting = intval(krfsapp_getMeta('_setting_products_per_page'));

    // Set up query arguments
    $args = array(
        'post_type' => 'product', // Product post type
        'posts_per_page' => $products_per_page_setting, // Number of products per page
        'post_status' => 'publish', // Only published products
        'post__in' => $product_ids, // Filter products by IDs if provided
        'orderby' => 'post__in', // Maintain the order of product IDs as provided
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat', // Product category taxonomy
                'field' => 'slug', // Use 'slug' to match the category
                'terms' => $category_slug, // Pass the category slug dynamically
            ),
        ),
    );

    // Custom product query
    $query = new WP_Query($args);

    // Start HTML for product grid
    $html = '';
    $count = 0;

    // Set default shape and metal
    if(empty($filters['shape'])) {
        $filters['shape'] = 'round';
    }
    if(empty($filters['metal'])) {
        $filters['metal'] = 'white_gold';
    }


    global $krfsapp_filters;
    $krfsapp_filters = $filters;

    global $krfsapp_attributes_mapping;
    $krfsapp_attributes_mapping = json_decode(krfsapp_getMeta('attributes_mapping'), true);

    $MetalTermItems = json_decode(krfsapp_getMeta('metal_attr_advance_filters'), true);

    global $kirb_all_metal_term_slugs;
    $kirb_all_metal_term_slugs = array_map(function($item) {
        global $krfsapp_attributes_mapping;

        $key = str_replace("metal_", "", $item['slug']);

        return isset($krfsapp_attributes_mapping['metal_terms'][$key])
            ? $krfsapp_attributes_mapping['metal_terms'][$key]
            : null; // or fallback value like $key
    }, $MetalTermItems);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            global $product; // Access the WooCommerce product object

            // Get the product ID
            $product_id = get_the_ID();

            // Get the price from the $filters_data array using the product ID
            $price = isset($product_prices[$product_id]) ? $product_prices[$product_id] : '';

            // Start output buffering
            ob_start();

            // Include template for product item
            include('src/'.KRFSAPP_THEME.'/ui/prod-item-grid-krfs.php');

            // Pass the price to the HTML (you can modify the template file to display the price)

            // Append the output to HTML
            $html .= ob_get_clean();

            $count++;
        }
    } else {
        $html = '<p>No products found</p>';
    }

    // Restore original Post Data
    wp_reset_postdata();

    return array('html' => $html, 'count' => $count, 'pagination' => $pagination);
}

function krfsapp_initial_product_listing($catg, $uri_components) {
    global $krfsapp_maxprice, $krfsapp_minprice;
    $filters = array(
        'category' => $catg,
        'page' => 1,
        'filters_uri' => array(
            'shape' => isset($uri_components['shape']) ? str_replace("shape_","", sanitize_text_field(wp_unslash($uri_components['shape']))) : '',
            'stone' => isset($uri_components['stone']) ? str_replace("sidestone_","", sanitize_text_field(wp_unslash($uri_components['stone']))) : '',
            // 'style' => isset($uri_components['style']) ? preg_replace('/^(style_|wedmen_)/', '', sanitize_text_field(wp_unslash($uri_components['style']))) : '',
            // 'metal' => isset($uri_components['metal']) ? str_replace("metal_","",sanitize_text_field(wp_unslash($uri_components['metal']))) : '',
            'minprice' => isset($uri_components['minprice']) ? floatval($uri_components['minprice']) : $krfsapp_minprice,
            'maxprice' => isset($uri_components['maxprice']) ? floatval($uri_components['maxprice']) : $krfsapp_maxprice,
            'sort' => isset($uri_components['sort']) ? sanitize_text_field(wp_unslash($uri_components['sort'])) : "Orderbyupdatedate-desc",
            'result_set' => isset($uri_components['result_set']) ? sanitize_text_field(wp_unslash($uri_components['result_set'])): '',
            "home_preview" => isset($_GET['home_preview']) ? sanitize_text_field(wp_unslash($_GET['home_preview'])) : ''
        )
    );

    // for styles array
    if (isset($uri_components['style']) && !empty($uri_components['style'])) {
        $uri_components['style'] = array_values($uri_components['style']); // formatting indexes
        foreach($uri_components['style'] as $style) {
            $filters['filters_uri']['style'][] = preg_replace('/^(style_|wedmen_|wedwomen_)/', '', sanitize_text_field(wp_unslash($style)));
        }
    }

    $filters['filters_uri']['style_taxonomy'] = 'pa_krfs_style_attr'; 

    if(isset($uri_components['style'][0]) && !empty($uri_components['style'][0])) {
        if (str_contains($uri_components['style'][0], 'wedmen_')) {
            $filters['filters_uri']['style_taxonomy'] = 'pa_krfs_wed_men_attr';
        } elseif (str_contains($uri_components['style'][0], 'wedwomen_')) {
            $filters['filters_uri']['style_taxonomy'] = 'pa_krfs_wed_women_attr';
        }
    }

    // for metals array
    if (isset($uri_components['metal']) && !empty($uri_components['metal'])) {
        foreach($uri_components['metal'] as $metal) {
            $filters['filters_uri']['metal'][] = str_replace("metal_","",sanitize_text_field(wp_unslash($metal)));
        }
    }

    $product_data = krfsapp_fetch_products_by_attributes($filters['filters_uri'], $catg, $filters['page']);
    $resp = krfsapp_prepare_ring_listing($product_data['products'], $catg, $product_data['pagination'], $filters['filters_uri']);
    return $resp;
}

function krfsapp_update_advance_filters($existing, $incoming) {
    $updated = [];

    // Create maps for quick lookup, but only include items that have a non-empty 'name'
    $incomingMap = array_column(array_filter($incoming, fn($item) => !empty ($item['slug'])), null, 'slug');
    $existingMap = array_column(array_filter($existing, fn($item) => !empty ($item['slug'])), null, 'slug');
    // Include all existing items, updating their state based on incoming data
    foreach ($existing as $item) {
        // Ensure the name is valid
        $name = $item['slug'] ?? '';
        if (!empty($name)) {
            if (isset($incomingMap[$name])) {
                // If the incoming data exists, update its state but retain other fields
                $updatedItem = $incomingMap[$name];
                $updated[] = array_merge($item, [
                    'enabled' => $updatedItem['enabled'] === true // Update 'enabled' field
                ]);
            } else {
                // Retain existing state if no update, including custom fields
                $updated[] = $item;
            }
        }
    }

    // Include new incoming items that were not present in existing data
    foreach ($incoming as $item) {
        $name = $item['slug'] ?? '';
        if (!empty($name) && !isset($existingMap[$name])) {
            $updated[] = $item; // Add new items with all fields intact
        }
    }

    return $updated;
}


function krfsapp_edit_advance_filters($attribute_array, $newvalue, $oldvalue, $prefixSlug,$categoryName) {
    if ($newvalue == $oldvalue) {
        return $attribute_array;
    }
    
     // Check if the new slug already exists (excluding the current attribute being updated)
     foreach ($attribute_array as $attribute) {
        if ($attribute['name'] === $newvalue) {
            // If the slug exists, return the array without making changes
            return false;
        }
    }
    foreach ($attribute_array as &$attribute) {
        // Check if the current name matches the old value
        if ($attribute['name'] === $oldvalue) {
            // Update the name field only
            $attribute['name'] = $newvalue;
            $attribute['slug'] = $prefixSlug . str_replace(' ', '_', $newvalue);
            // Add predefined terms for this attribute if provided
            krfsapp_addTermsToTaxonomy($newvalue,str_replace(' ', '_', $newvalue),$categoryName);
        }
    }

    return $attribute_array;
}

function krfsapp_addTermsToTaxonomy($term,$slug,$taxonomyName) {
    if (!term_exists($slug, 'pa_krfs_' . $taxonomyName)) {
        wp_insert_term(
            $term,
            'pa_krfs_' . $taxonomyName,
            array(
                'slug' => $slug // Set the custom slug
            )
        );
    }
}


function krfsapp_advance_filter_item($attribute_name, $attribute_slug, $terms = array())
{
    // Get the existing data for this attribute slug
    $existing_data = krfsapp_getMeta($attribute_slug);

    // Decode the existing data (if any)
    if ($existing_data !== false) {
        $advanced_filter_data = json_decode($existing_data, true);
    } else {
        $advanced_filter_data = array(); // Initialize as an empty array if no existing data
    }

    // Add new terms to the array for the given attribute slug
    foreach ($terms as $data) {
        // Check if the term is already in the array to avoid duplicates
        $term_exists = false;
        foreach ($advanced_filter_data as $term) {
            if ($term['name'] === $data) {
                $term_exists = true;
                break;
            }
        }

        if (!$term_exists) {
            $advanced_filter_data[] = array(
                'enabled' => true,
                'name' => $data,
                'slug' => strtolower($attribute_name . '_' . strtolower(str_replace(" ","_",$data)))
            );
        }
    }

    // Encode the updated data to JSON format
    $json_data = wp_json_encode($advanced_filter_data);

    // Store the updated data back into the database using the attribute slug as the key
    krfsapp_addMeta($attribute_slug . '_advance_filters', $json_data);
}

function krfsapp_create_custom_product_attribute($attribute_name, $attribute_slug, $terms = array()) {
    if ($attribute_slug == "style_attr" || $attribute_slug == "metal_attr" || $attribute_slug == "shape_attr" || $attribute_slug == "stone_attr" || $attribute_slug=="wed_men_attr"||$attribute_slug=="wed_women_attr"||$attribute_slug=="side_stone_attr") {
        krfsapp_advance_filter_item($attribute_name, $attribute_slug, $terms);
    }
    global $wpdb;

    // Ensure the slug is lowercased and valid
    $attribute_slug = strtolower($attribute_slug);

    // Check if the attribute already exists
    $existing_attributes = wc_get_attribute_taxonomies();
    $attribute_exists = false;

    foreach ($existing_attributes as $attribute) {
        if ($attribute->attribute_name === $attribute_slug || $attribute->attribute_name === 'krfs_'.$attribute_slug) {
            $attribute_exists = true;
            break;
        }
    }

    // If the attribute does not exist, create it
    if (!$attribute_exists) {
        // Insert the attribute into the WooCommerce system
        $wpdb->insert(
            $wpdb->prefix . 'woocommerce_attribute_taxonomies',
            array(
                'attribute_label' => $attribute_name,
                'attribute_name' => 'krfs_'.$attribute_slug,
                'attribute_type' => 'select',
                'attribute_orderby' => 'menu_order',
                'attribute_public' => 1
            )
        );

        // Clear WooCommerce attribute cache
        delete_transient('wc_attribute_taxonomies');

        // Register the attribute as a taxonomy
        register_taxonomy(
            'pa_krfs_' . $attribute_slug,
            'product',
            array(
                'labels' => array(
                    'name' => $attribute_name
                ),
                'hierarchical' => true,
                'show_ui' => true,
                'query_var' => true,
                'rewrite' => array('slug' => 'pa_krfs_' . $attribute_slug),
            )
        );

        // Update WooCommerce attribute taxonomies
        update_option('woocommerce_attribute_taxonomies', wc_get_attribute_taxonomies());

        // Flush rewrite rules to update permalinks
        flush_rewrite_rules();
    }
    // Add predefined terms for this attribute if provided
    if (!empty($terms) && is_array($terms)) {
        foreach ($terms as $term) {
            $custom_slug = strtolower(str_replace(' ', '_', $term));
            if (!term_exists($term, 'pa_krfs_' . $attribute_slug)) {
                wp_insert_term(
                    $term,
                    'pa_krfs_' . $attribute_slug,
                    array(
                        'slug' => $custom_slug // Set the custom slug
                    )
                );
            }
        }
    }
}

/**
 * Generic function to process and update attributes.
 *
 * @param array $attributes List of attributes to process.
 * @param array $enabledAttributes List of enabled attributes (e.g., from POST data).
 * @param callable $updateCallback Callback function to handle the updated attributes.
 * @param string $metaKey Meta key to store the updated attributes (optional).
 *
 * @return void
 */
function krfsapp_processAndUpdateFilterAttributes(array $attributes, array $enabledAttributes, callable $updateCallback, string $metaKey = '') {
    $formattedAttributes = [];

    foreach ($attributes as $attribute) {
        $enabled = in_array($attribute['slug'], $enabledAttributes, true);

        $formattedAttributes[] = [
            'enabled' => $enabled,
            'name'    => $attribute['name'],
            'slug'    => $attribute['slug']
        ];
    }

    $updatedAttributes = $updateCallback($attributes, $formattedAttributes);
    if ($metaKey) {
        krfsapp_addMeta($metaKey, wp_json_encode($updatedAttributes));
    }
}


/**
 * Generic function to process and update setting controls.
 *
 * @param array $settings control List of attributes to process.
 * @param array $enabledSettings List of enabled setting controls (e.g., from POST data).
 * @return void
 */
function krfsapp_updateFilterSettingsControl(array $settings,array $enabledSettings ) {
   
    foreach ($enabledSettings as $key => $value) {
        // Set to true if "on", otherwise false
        $settings[$key] = ($value === 'on');
    }
    // Update the meta with the new settings
    krfsapp_addMeta('_setting_section_controls', wp_json_encode($settings));
}

/**
 * Generic function to add new filter in collection.
 * @return boolean
 */
function krfsapp_handleAddCollectionFilters( $newFilterValue, $attributes, $metaKey, $prefix, $categoryName) {
    $newSlug = $prefix . str_replace(' ', '_', $newFilterValue);
    if (!krfsapp_slugExists($attributes, $newSlug)) {
        $newAttribute = [
            "enabled" => true,
            "name" => $newFilterValue,
            "custom" => "true",
            "slug" => $newSlug
        ];
        $attributes[] = $newAttribute;
        krfsapp_addMeta($metaKey, wp_json_encode($attributes));
        // Add predefined terms for this attribute if provided
        krfsapp_addTermsToTaxonomy($newFilterValue,str_replace(' ', '_', $newFilterValue),$categoryName);
        
        return true;
    }else
    {
        return false;
    }
}
/**
 * Generic function to edit custom filter name in collection.
 * @return boolean
 */
function krfsapp_handleEditCollectionFilters($newValue,$oldValue,$categoryName,$attributesMapping) {

    if (!empty($newValue) && !empty($oldValue) && isset($attributesMapping[$categoryName])) {
        $config = $attributesMapping[$categoryName];
        if(!$updatedAttributes = krfsapp_edit_advance_filters($config['attributes'], $newValue, $oldValue, $config['prefix'],$categoryName)){
            return false;
        }
        krfsapp_addMeta($config['metaKey'], wp_json_encode($updatedAttributes));
        return true;
    }
}


function krfsapp_get_min_max_price_by_category($category_slug) {
    global $wpdb;

    $category_slug = sanitize_text_field($category_slug);

    $result = $wpdb->get_row($wpdb->prepare(
    "
        SELECT 
            MIN(CAST(pm.meta_value AS DECIMAL(10,2))) AS min_price,
            MAX(CAST(pm.meta_value AS DECIMAL(10,2))) AS max_price
        FROM {$wpdb->postmeta} pm
        INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
        INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
        WHERE p.post_type = 'product' 
        AND p.post_status = 'publish'
        AND pm.meta_key = '_price'
        AND tt.taxonomy = 'product_cat'
        AND t.slug = %s
    ",
        $category_slug
    ));


    $min = $result->min_price ?? 50;
    $max = $result->max_price ?? 100;
    
    if($min == $max) {
        $min = 50;
    }

    return [
        'min_price' => $min,
        'max_price' => $max,
    ];
}

function krfsapp_get_parent_slug($product) {
    $product_cat_ids = $product->get_category_ids();

    $parent_catgs = array();

    if (!empty($product_cat_ids)) {
        foreach($product_cat_ids as $cat_id) {
            $product_cat = get_term_by('id', $cat_id, 'product_cat');
            // Loop through to find the topmost parent category
            while ($product_cat->parent != 0) {
                $product_cat = get_term_by('id', $product_cat->parent, 'product_cat');
            }
            array_push($parent_catgs, $product_cat->slug);
        }
    }
    
    return $parent_catgs;
}

function krfsapp_getRingSizeList() {
    $ring_size_country = "r1";

    $ringSizeData = array();

    $ringSizeData['r1'] = array();
    for($i = 2; $i <= 16; $i+=0.25) {
        $ringSizeData['r1'][] = $i;
    }

    $ringSizeData['r2'] = array();
    $r2_alpha = range('F', 'Z');
    foreach($r2_alpha as $alpha) {
        $ringSizeData['r2'][] = $alpha;
        if($alpha != "I") {
            $ringSizeData['r2'][] = $alpha . " 1/2";
        }
    }

    $ringSizeData['r3'] = array();
    $r3_halfs = array(45,47,48,50,52,54,56,58,60,61,63,65,67,69);
    for($i = 44; $i <= 70; $i++) {
        $ringSizeData['r3'][] = $i;
        if(in_array($i, $r3_halfs)) {
            $ringSizeData['r3'][] = $i + 0.5;
        }
    }

    $ringSizeData['r4'] = array();
    for($i = 14; $i <= 22; $i++) {
        $ringSizeData['r4'][] = $i;
        if($i != 22) {
            if($i != 20) {
                $ringSizeData['r4'][] = $i.' 1/4';
            }
            $ringSizeData['r4'][] = $i.' 1/2';
            $ringSizeData['r4'][] = $i.' 3/4';
        }
    }

    $ringSizeData['r5'] = range(4, 27);
    $ringSizeData['r6'] = array("4", "4 5/8", "5 1/4", "5 7/8", "6 1/2", "7 1/8", "7 3/4", "8 3/8", "9", "9 5/8", "10 1/4", "10 7/8", "11 1/2", "12 1/8", "12 3/4", "13 3/8", "14", "14 5/8", "15 1/4", "15 7/8", "16 1/2", "17 1/8", "17 3/4", "18 3/8", "19", "19 5/8", "20 1/4", "20 7/8", "21 1/2", "22 1/8", "22 3/4", "23 3/8", "24", "24 5/8", "25 1/4", "25 7/8", "26 1/2", "27 1/8", "27 3/4", "28 3/8", "29");
    $ringSizeData['r7'] = range(5, 30);

    $ringSizeData['r8'] = array();
    $r8_alpha = range('H', 'Z');
    foreach($r8_alpha as $alpha) {
        $ringSizeData['r8'][] = $alpha;
        $ringSizeData['r8'][] = $alpha . " 1/2";
        if($alpha == 'Z') {
            $ringSizeData['r8'][] = $alpha . " + 1";
            $ringSizeData['r8'][] = $alpha . " + 1 1/2";
        }
    }
    if(isset($ringSizeData[$ring_size_country])) {
        return $ringSizeData[$ring_size_country];
    }
    return $ringSizeData['r1'];
}


function krfsapp_register_plugin() {
    $url = KRFSAPP_ENDPOINT_URL . "/install-app";
    $shop_email = krfsapp_getMeta("_shop_email");
    $shop_name = krfsapp_getMeta("_shop_name");
    $current_domain = sanitize_text_field($_SERVER['HTTP_HOST']);

    $user_info = json_decode(krfsapp_getMeta('_user_info'), true);
    $user_info['phone'] = isset($user_info['phone']) ? $user_info['phone'] : '';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 30,
        'body' => wp_json_encode(array(
            "email" => $shop_email,
            "currency_format" => get_woocommerce_currency(),
            "shop" => $shop_name,
            "domain" => $current_domain,
            "user_info" => $user_info,
        )),
    ));

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    if($data['type'] == 'success') {
        krfsapp_addMeta("_store_token", $data['store_token']);
        krfsapp_addMeta("_shop_name", $data['storeUrl']);
        krfsapp_addMeta("_shop_email", $shop_email);
    }else{
        set_transient('krfs_deactivation_message', "Plugin can't be activated properly, please try again!", 60);
        deactivate_plugins(plugin_basename(KRFSAPP_BASE_DIR . 'keyideas-jewelry-ring-filter-search-pro.php'));
    }
    krfsapp_addMeta('_is_plugin_active', 'true');
}

function krfsapp_init_activation($permission = false) {
    $user_info = array();
    $user_info['name'] = get_bloginfo('name');
    $user_info['company_name'] = get_bloginfo('name');
    $user_info['phone'] = '';
    $user_info['country'] = get_bloginfo('language');

    if($permission) {
        $shop_email = get_option('admin_email');
    } else {
        $shop_email = "appuser@keyideasjewelry.com";
    }

    $shop_email = "krfs_client_".time()."_".$shop_email;

    $user_info['email'] = $shop_email;

    $shop_name = explode("@", $shop_email)[0] . "-krfs-".krfsapp_gen_uuidv4()."-shop";

    krfsapp_addMeta("_shop_name", $shop_name);
    krfsapp_addMeta("_shop_email", $shop_email);

    $user_info['country'] = explode('-', $user_info['country'])[1];
    $country_data = json_decode(krfsapp_file_get_contents(KRFSAPP_PLUGIN_DIR . '/assets/country-codes.json'), true);
    foreach($country_data as $country){
        if($country['code'] == $user_info['country']){
            $user_info['country'] = $country['name'];
            break;
        }
    }

    $user_info['website_url'] = site_url();
    krfsapp_addMeta('_user_info',wp_json_encode($user_info));
    krfsapp_register_plugin();
}

function krfsapp_plugin_uninstall_email() {
    $user_info = krfsapp_getMeta('_user_info');
    if($user_info) {
        $url = KRFSAPP_ENDPOINT_URL . "/send-woo-mails";
        $shop_name = krfsapp_getMeta("_shop_name");
        $token = krfsapp_getMeta("_store_token");

        $user_info = json_decode($user_info, true);
        wp_remote_post($url, array(
            'method' => 'POST',
            'timeout' => 30,
            'headers' => [
                'shop'  => $shop_name,
                'token' => $token
            ],
            'body' => wp_json_encode(array(
                "storeOwner" => $user_info['name'] ?? '',
                "subject"=> "Plugin Uninstall",
                "company"=> $user_info['company_name'] ?? '',
                "ownerEmail"=> $user_info['email'] ?? ''
            )),
        ));
    }
}

/* phpcs:enable */
