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

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

function kirb_getShapeErrorImage($shape) {
    $shape = strtolower($shape);
    return KIRB_PLUGIN_DIR . '/assets/diamond_icons/' . $shape . '-icon.png';
}

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

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

function kirb_downloadAndCacheFile($url, $cache_key, $token = '', $force_no_cache = false, $cache_time = KIRB_CACHE_DATA_TIME) {
    // Check cache first
    if (!$force_no_cache && KIRB_CACHE_ENABLED) {
        $data = kirb_get_cache_db($cache_key);
        if ($data !== false && (!isset($data['type']) || $data['type'] !== 'error')) {
            return $data;
        }
    }

    // Get shop name (used in request headers)
    $shop_name = kirbGetMeta('_shop_name');
    if (!$shop_name) {
        return false;
    }

    // Fetch from remote
    $response = wp_remote_get($url, [
        'headers' => [
            'shop'  => $shop_name,
            'token' => $token
        ],
        'timeout' => 30,
    ]);

    // Fallback to old cache if request failed
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        $fallback = kirb_get_cache_db($cache_key);
        if ($fallback !== false) return $fallback;
        return false;
    }

    // Get and decode response body
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    // Save new data to cache
    if ($data !== null) {
        kirb_set_cache_db($cache_key, $data, $cache_time * 60); // cache_time in minutes
    }

    return $data;
}



function kirb_set_cache_db($key, $value, $expiration_seconds) {
    global $wpdb;

    $table = $wpdb->prefix . 'kirb_cache';
    $expires = time() + $expiration_seconds;
    $serialized_value = maybe_serialize($value);

    $wpdb->replace(
        $table,
        [
            'cache_key'   => $key,
            'cache_value' => $serialized_value,
            'expires_at'  => $expires,
        ],
        [
            '%s', // cache_key
            '%s', // cache_value
            '%d'  // expires_at
        ]
    );
}


function kirb_get_cache_db($key) {
    global $wpdb;

    $row = $wpdb->get_row(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is internal constant
        $wpdb->prepare("SELECT cache_value, expires_at FROM {$wpdb->prefix}kirb_cache WHERE cache_key = %s", $key),
        ARRAY_A
    );

    if (!$row) return false;

    if (time() > (int) $row['expires_at']) {
        kirb_delete_cache_db($key);
        return false;
    }

    return maybe_unserialize($row['cache_value']);
}

function kirb_delete_cache_db($key) {
    global $wpdb;

    $table = $wpdb->prefix . 'kirb_cache';
    $wpdb->delete($table, ['cache_key' => $key], ['%s']);
}

function kirb_get_filters_data() {
    $url = KIRB_ENDPOINT_URL . '/get-data';
    $data = kirb_downloadAndCacheFile($url, 'kirb-filters-cache.json');
    return $data;
}

function kirb_get_diamonds($filters, $force_no_cache = false, $cache_time = KIRB_CACHE_DATA_TIME) {
    $kirb_store_token = kirbGetMeta("_store_token");
    $currency = get_woocommerce_currency();
    $force_zero = $filters['force_zero'] ?? false;

    if($force_zero) {
        return null;
    }

    if(!$kirb_store_token || ($kirb_store_token && empty($kirb_store_token))) {
        return false;
    }
    if (isset($filters['type']) && $filters['type'] == 'custom') {
        $products = $filters['products']; // array of products
        $cpy_prods = $products;
        sort($cpy_prods);
        $uid = md5(
            wp_json_encode( 
                array(
                    'type' => 'custom',
                    'products' => $cpy_prods
                )
            )
        );
        $products = implode(',', $products);
        $url = KIRB_ENDPOINT_URL . '/get-products-list?pid=' . $products . '&currency=' . $currency;
        $file = 'kirb-diamonds-cache-' . $uid . '.json';
        $data = kirb_downloadAndCacheFile($url, $file, $kirb_store_token, $force_no_cache, $cache_time);
        return $data;
    } else {
        global $kirb_filters_data;
        if(!$kirb_filters_data) {
            $kirb_filters_data = kirb_get_filters_data();
        }
        $max_diamonds = KIRB_ITEMS_PER_PAGE;
        $catg = $filters['category'];
        $page = $filters['page'];
        $filters['max_diamonds'] = $max_diamonds;
        $uid = md5(serialize($filters));
        $offset = ($page - 1) * $max_diamonds;
        $catg_id = "";
        foreach ($kirb_filters_data['categories'] as $category) {
            if (strtolower($category['name']) == strtolower($catg)) {
                $catg_id = $category['_id'];
                break;
            }
        }

        // Prepare filters URI
        $filters_uri = "";
        if (isset($filters['filters_uri'])) {
            $filters_uri = $filters['filters_uri'];
        }

        // Prepare search URI
        if (!empty($filters['search'])) {
            // Reverse translate the search query
            $filters['search'] = kirb_string_reverse_translate($filters['search']);
            $filters_uri = "&searchQuery=" . $filters['search'];
        }

        if(!str_starts_with($filters_uri, "&")) {
            $filters_uri = "&" . $filters_uri;
        }

        if (!empty($catg_id)) {
            $url = KIRB_ENDPOINT_URL . '/get-product?dtypeid=' . $catg_id . '&currency=' . $currency . '&limit=' . $max_diamonds . '&offset=' . $offset . $filters_uri;
            $file = 'kirb-diamonds-cache-' . $uid . '.json';
            $data = kirb_downloadAndCacheFile($url, $file, $kirb_store_token, $force_no_cache, $cache_time);
            return $data;
        }
    }
}

function kirb_get_valid_filters_keys() {
    return array(
        'mincarat', 'maxcarat', 'color', 'cut', 'clarity', 'shape', 'minprice', 'maxprice',
        'polish', 'symmetry', 'fluor', 'mintable', 'maxtable', 'mindepth', 'maxdepth',
        'minratio', 'maxratio', 'gemType', 'intensity', 'labFilter', 'videoAvailable', 'includeShippingDaysFilter', 'sort'
    );
}

function kirb_parse_filters_uri($params) {
    $parameterKeys = kirb_get_valid_filters_keys();
    $skip_keys = array();
    // Temp Off
    // if(isset($params['shape']) && strtolower($params['shape'])  == 'round') {
    //     $skip_keys = array('cut');
    // }
    $uriSegments = [];
    foreach ($parameterKeys as $key) {
        if (isset($params[$key]) && !empty($params[$key]) && !in_array($key, $skip_keys)) {
            if ($key === 'sort') {
                $uriSegments[] = "orderby=" . sanitize_text_field($params[$key]);
            } else {
                $uriSegments[] = $key . "=" . sanitize_text_field($params[$key]);
            }
        }
    }
    return implode("&", $uriSegments);
}

function kirb_prepare_custom_listing($config) {
    $filter = array(
        'type' => 'custom',
        'products' => $config['products'],
    );
    $diamonds_data = kirb_get_diamonds($filter, false, KIRB_CACHE_RC_ITEMS);
    $diamonds = $diamonds_data['product'];

    if ($diamonds != null) {
        // Sort the $diamonds array based on their positions in $config['products']
        $configProductsPositions = array_flip($config['products']);
        usort($diamonds, function ($a, $b) use ($configProductsPositions) {
            return $configProductsPositions[$a['_id']] - $configProductsPositions[$b['_id']];
        });

        global $kirb_page_ids;
        $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);
        
        global $kirb_filters_data, $kirb_site_config;
        if(!$kirb_filters_data) {
            $kirb_filters_data = kirb_get_filters_data();
        }

        if(!$kirb_site_config) {
            $kirb_site_config = kirb_get_config_file();
        }
        
        global $kirb_disable_byor;
        $kirb_disable_byor = !kirbGetMeta('_setting_ring_setting_catg');
        
        require_once(KIRB_BASE_DIR . '/translations_lookup.php');

        $html = "";
        $count = 0;
        foreach ($diamonds as $diamond) {
            ob_start();
            include ("ui/prod-item-list.php");
            $html .= ob_get_clean();
            $count++;
        }
        return array('html' => $html, 'count' => $count);
    } else {
        return array('html' => '<div>Empty Response!</div>', 'count' => 0);
    }
}

function kirb_prepare_diamond_listing($filters) {
    $diamonds_data = kirb_get_diamonds($filters, false, KIRB_CACHE_LISTING_PAGE);
    $diamonds = $diamonds_data['data'] ?? [];
    $output = '';
    $count = 0;
    $list_html = "";
    $grid_html = "";

    global $kirb_page_ids;
    $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);
    global $kirb_filters_data, $kirb_site_config;
    
    if(!$kirb_filters_data) {
        $kirb_filters_data = kirb_get_filters_data();
    }

    if(!$kirb_site_config) {
        $kirb_site_config = kirb_get_config_file();
    }

    global $kirb_disable_byor;
    $kirb_disable_byor = !kirbGetMeta('_setting_ring_setting_catg');

    // Translation Lookup
    require_once(KIRB_BASE_DIR . '/translations_lookup.php');

    foreach ($diamonds as $diamond) {
        ob_start();
        include ("ui/prod-item-list.php");
        $list_html .= ob_get_clean();
        ob_start();
        include ("ui/prod-item-grid.php");
        $grid_html .= ob_get_clean();
        $count++;
    }

    $kirb_empty_msg = "No result found. Please contact us to speak to a gemologist to help you find the perfect stone.";

    if($count == 0) {
        $list_html = '
            <tr class="kirb_empty_err">
                <td colspan="11" style="padding: 20px;"> ' .$kirb_empty_msg . '</td>
            </tr>
        ';
        $grid_html = '
            <div style="line-height: normal;font-size:16px;font-weight:600;" class="kirb_empty_err">' . $kirb_empty_msg . '</div>
        ';
    }

    $resp = array(
        'list_html' => $list_html,
        'grid_html' => $grid_html,
        'stats' => array(
            'count' => $count,
            'items_per_page' => KIRB_ITEMS_PER_PAGE
        )
    );
    if ($filters['page'] == 1) {
        $diamonds_data['count'] = $diamonds_data['count'] ?? 0;
        $total_pages = ceil($diamonds_data['count'] / KIRB_ITEMS_PER_PAGE);
        $resp['stats']['total_count'] = $diamonds_data['count'] == null ? 0 : $diamonds_data['count'];
        $resp['stats']['total_pages'] = $total_pages;
    }
    return $resp;
}

function kirb_diamond_listing_wrapper_code($is_empty, $catg, $html) {
    
    $kirb_empty_msg = "No result found. Please contact us to speak to a gemologist to help you find the perfect stone.";

    if($is_empty) {
        return '
            <div class="kirb_empty_msg">
                ' . $kirb_empty_msg . '
            </div>
        ';
    }else{
        return '
            <table id="product-list-view">
                <thead>
                    <tr class="heading">
                        '.kirb_getDiamondListingHeaders("listing",$catg).'
                    </tr>
                </thead>
                <tbody id="kirb_product_list">
                    '.$html.'
                </tbody>
            </table>
        ';
    }
}

function kirb_arrayIntersectionIgnoreCase($array1, $array2) {
    // Convert both arrays to lowercase
    $lowercaseArray1 = array_map('strtolower', $array1);
    $lowercaseArray2 = array_map('strtolower', $array2);

    // Find intersection
    $intersection = array_intersect($lowercaseArray1, $lowercaseArray2);

    // Map back to original values (preserving the case of the first array)
    $originalIntersection = array_values(array_filter($array1, function($item) use ($intersection) {
        return in_array(strtolower($item), $intersection);
    }));

    return $originalIntersection;
}

function kirb_initial_diamond_listing($list_type, $catg, $init_filters) {

    $uri_segments = array();
    $parameterKeys = kirb_get_valid_filters_keys();

    global $kirb_filters_data, $kirb_site_config;
    if(!$kirb_filters_data) {
        $kirb_filters_data = kirb_get_filters_data();
    }

    if(!$kirb_site_config) {
        $kirb_site_config = kirb_get_config_file();
    }

    foreach ($parameterKeys as $key) {
        if (isset($_GET[$key])) {
            // reading GET for filters only; nonce not required for view. Unslash then sanitize.
            $uri_segments[$key] = sanitize_text_field( wp_unslash( $_GET[$key] ) );
        }
    }

    $init_filters_arr = array();
    
    if($catg == 'NATURAL' || $catg == 'LAB CREATED') {
        $sort_by_values = array('popular', 'Orderbyprice-asc', 'Orderbyprice-desc', 'Orderbycarat-asc', 'Orderbycarat-desc', 'Orderbycolor-asc', 'Orderbycolor-desc', 'Orderbyclarity-asc', 'Orderbyclarity-desc', 'Orderbycut-asc', 'Orderbycut-desc');

        $init_filters_arr = array(
            'shape' => implode(",", array_map(fn($shape) => strtolower($shape['name']), $init_filters['shape'])),
            'mincarat' => $init_filters['caratRange']['minCarat'],
            'maxcarat' => $init_filters['caratRange']['maxCarat'],
            'color' => $init_filters['color'], 
            'cut' => strtolower($init_filters['cut']), 
            'clarity' => str_replace("/",",",$init_filters['clarity']),
            'minprice' => $init_filters['priceRange']['minSaleAmt'], 
            'maxprice' => $init_filters['priceRange']['maxSaleAmt'],
            'polish' => strtolower($init_filters['polish']), 
            'symmetry' => strtolower($init_filters['symmetry']),
            'fluor' => strtolower($init_filters['fluor']), 
            'mintable' => $init_filters['taRange']['minTa'], 
            'maxtable' => $init_filters['taRange']['maxTa'], 
            'mindepth' => $init_filters['tdRange']['minTd'], 
            'maxdepth' => $init_filters['tdRange']['maxTd'],
            'minratio' => $init_filters['Ratio']['min'], 
            'maxratio' => $init_filters['Ratio']['max'],
            'labFilter' => isset($init_filters['labFilter']) ? $init_filters['labFilter'] : "",
            'sort' => 'popular', // Default sort
        );
    }else if($catg == 'GEMSTONE') {
        $sort_by_values = array('popular', 'Orderbyprice-asc', 'Orderbyprice-desc', 'Orderbycarat-asc', 'Orderbycarat-desc');

        $init_filters_arr = array(
            'shape' => implode(",", array_map(fn($shape) => strtolower($shape['name']), $init_filters['shape'])),
            'color' => $init_filters['gem_color'], 
            'mincarat' => $init_filters['caratRange']['minCarat'],
            'maxcarat' => $init_filters['caratRange']['maxCarat'],
            'minprice' => $init_filters['priceRange']['minSaleAmt'], 
            'maxprice' => $init_filters['priceRange']['maxSaleAmt'],
            'gemType' => $init_filters['gem_type'], 
            'sort' => 'popular', 
        );
    }else if($catg == 'COLORED DIAMONDS') {
         $sort_by_values = array('popular', 'Orderbyprice-asc', 'Orderbyprice-desc', 'Orderbycarat-asc', 'Orderbycarat-desc','Orderbyclarity-asc', 'Orderbyclarity-desc');

        $init_filters_arr = array(
            'shape' => implode(",", array_map(fn($shape) => strtolower($shape['name']), $init_filters['shape'])),
            'color' => $init_filters['gem_color'], 
            'mincarat' => $init_filters['caratRange']['minCarat'],
            'maxcarat' => $init_filters['caratRange']['maxCarat'],
            'minprice' => $init_filters['priceRange']['minSaleAmt'],
            'maxprice' => $init_filters['priceRange']['maxSaleAmt'],
            'clarity' => str_replace("/",",",$init_filters['clarity']),
            'intensity' => $init_filters['intensity'],
            'sort' => 'popular',
        );
    }

    
    $addons_data = json_decode(kirbGetMeta('_setting_addon_data'), true);
    $default_sort = isset($addons_data['default_sort']['select']) ? $addons_data['default_sort']['select'] : 'popular' ;   
                                    
    if (in_array($default_sort, $sort_by_values, true)) {
        $init_filters_arr['sort'] = $default_sort;
    }


    // Remove empty values
    $init_filters_arr = array_filter($init_filters_arr);

    // Merge arrays, keeping existing keys in $uri_segments
    $uri_segments += $init_filters_arr;

    // Filters Validation
    $filter_validation_keys = array('color','cut','clarity','polish','symmetry','fluor','labFilter');
    $range_validation_keys = array('mincarat','maxcarat','minprice','maxprice','mintable','maxtable','mindepth','maxdepth','minratio','maxratio');

    foreach ($uri_segments as $key => $value) {
        if(in_array($key, $range_validation_keys) && isset($init_filters_arr[$key])) {
            if(str_starts_with($key, "min")) {
                $min_val = max(array(floatval($value),floatval($init_filters_arr[$key])));
                $uri_segments[$key] = $min_val;
            }else if(str_starts_with($key, "max")) {
                $max_val = min(array(floatval($value),floatval($init_filters_arr[$key])));
                $uri_segments[$key] = $max_val;
            }
        }else if(in_array($key, $filter_validation_keys) && isset($init_filters_arr[$key])) {
            $valid_filter_arr = explode(",", $init_filters_arr[$key]);
            $uri_filter_arr = explode(",", $value);
            $uri_final_arr = kirb_arrayIntersectionIgnoreCase($uri_filter_arr, $valid_filter_arr);
            if(count($uri_final_arr) > 0) {
                $uri_segments[$key] = implode(",", $uri_final_arr);
            }else{
                $uri_segments[$key] = implode(",", $valid_filter_arr);
            }
        }
    }

    // Check if the shape is set in the URL
    $url_shape_preset = get_query_var('kirb_param');
    $shape_slug_config = kirb_get_config("listing_shape_slugs");
    if($shape_slug_config && isset($shape_slug_config[$url_shape_preset])) {
        $url_shape_preset = $shape_slug_config[$url_shape_preset];
    }else{
        $url_shape_preset = "";
    }

    if($init_filters_arr['shape'] == $uri_segments['shape'] && !empty($url_shape_preset)) {
        $uri_segments['shape'] = $url_shape_preset;
    }

    // Shape exclusive check
    $force_zero = false;
    if(!str_contains($uri_segments['shape'],",") && !str_contains($init_filters_arr['shape'],$uri_segments['shape'])) {
        $force_zero = true;
    }

    $filters = array(
        'category' => $catg,
        'page' => 1,
        'filters_uri' => kirb_parse_filters_uri($uri_segments),
        'force_zero' => $force_zero
    );
    $resp = kirb_prepare_diamond_listing($filters);
    if ($list_type == 'grid') {
        return array(
            'html' => $resp['grid_html'],
            'stats' => $resp['stats']
        );
    } else {
        $complete_html = kirb_diamond_listing_wrapper_code(intval($resp['stats']['count']) == 0, $catg, $resp['list_html']);
        return array(
            'html' => $complete_html,
            'stats' => $resp['stats']
        );
    }
}

function kirb_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 kirb_getPageUrlById($page_id) {
    $page_slug = get_post_field( 'post_name', $page_id );
    return site_url() . '/' . $page_slug . '/';
}

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

    $page_id = kirb_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 kirb_create_pages($title, $content, $slug, $status)
{
    $new_status = $status ? 'publish' : 'draft';
    if (kirb_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 kirb_update_page_status($slug, $status);
    }
}

function kirb_make_diamond_name($diamond_carat, $diamond_color, $diamond_clarity, $diamond_cut, $diamond_shape, $diamond_certno)
{
    if ($diamond_shape == 'Round') {
        $combinetitle = $diamond_cut . "-" . $diamond_shape . "-cut-";
    } else {
        $combinetitle = $diamond_shape . "-cut-";
    }
    $diamond_name = $diamond_carat . "-carat-" . $diamond_color . "-color-" . $diamond_clarity . "-clarity-" . $combinetitle . $diamond_certno;
    if (!empty($diamond_name)) {
        return $diamond_name;
    }
}

function kirb_prepareDiamondSlug($diamond, $for_wc = false) {
    $combinetitle = "";
    if ($diamond['shape'] == 'Round') {
        $combinetitle = $diamond['cut'] . "-" . $diamond['shape'] . "-cut-";
    } else {
        $combinetitle = $diamond['shape'] . "-cut-";
    }
    if ($for_wc) {
        $combinetitle .= "diamond-";
    }
    if(!isset($diamond['clarity'])){
        return sanitize_title($diamond['weight'] . "-carat-" . $diamond['color'] . "-color-" . $combinetitle . $diamond['_id']);
    }
    return sanitize_title($diamond['weight'] . "-carat-" . $diamond['color'] . "-color-" . $diamond['clarity'] . "-clarity-" . $combinetitle . $diamond['_id']);
}


function kirb_make_diamond_description($diamond, $type){
    // if(empty($diamond_clarity)){
    //     return "$diamond_carat Carat - $diamond_color Color - $diamond_cut Cut - $diamond_shape $type with $cert_type certificate.";
    // }
    // return "$diamond_carat Carat - $diamond_color Color - $diamond_clarity Clarity - $diamond_cut Cut - $diamond_shape $type with $cert_type certificate.";
    return "
        ID: ".$diamond['_id']."\n
        Vendor Name: Nivoda \n
        Stock Number: ".$diamond['sku']."\n
        Lab Report Number: ".$diamond['lab_report_no']."\n
        Added on ".wp_date('d F Y', current_time('timestamp'))." by RingBuilder App\n
    ";
}

// if(!is_admin()) {
//     remove_filter('sanitize_title', 'sanitize_title_with_dashes');
// }

// Function to clean old cache files
function kirb_clean_old_cache() {
    global $wpdb;
    $current_time = time();
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}kirb_cache WHERE expires_at < %d",
            $current_time
        )
    );
}

function kirb_garbage_cleaner() {
    kirb_clean_old_cache();
    wp_send_json_success('Success!');
}

function kirb_getDiamondByUID($diamond_id, $force_no_cache = false)
{
    $diamond = kirb_get_diamonds(
        array(
            'type' => 'custom',
            'products' => array($diamond_id)
        )
    , $force_no_cache);
    if (isset($diamond['product']) && count($diamond['product']) > 0) {
        return array(
            'diamond' => $diamond['product'][0],
            'error' => false
        );
    }
    return array(
        'error' => true
    );
}

function kirb_getCurrentUserId()
{
    if (is_user_logged_in()) {
        $user = wp_get_current_user();
        return $user->ID;
    } else {
        return session_id();
    }
}

function kirb_getDiamondCategory($diamond_catg_id, $kirb_filters_data = null, $mapped_value = true) {
    if($kirb_filters_data == null) {
        $kirb_filters_data = kirb_get_filters_data();
    }
    $catg_name = "";
    foreach ($kirb_filters_data['categories'] as $category) {
        if ($category['_id'] == $diamond_catg_id) {
            $catg_name = $category['name'];
            break;
        }
    }
    if($mapped_value) {
        if (isset(KIRB_ALL_CATEGORIES_MAP[$catg_name])) {
            return KIRB_ALL_CATEGORIES_MAP[$catg_name];
        }
    }else{
        return $catg_name;
    }
    return false;
}

function kirb_fetch_rc_prods($products, $type) {
    if(!empty($products)) {
        $config = array(
            'products' => $products,
            'type' => $type
        );
        $m_resp = kirb_prepare_custom_listing($config);
        $resp = array(        
            'html' => $m_resp['html'],
            'stats' => array(
                'count' => $m_resp['count'],
            )
        );
        return $resp;
    }else{
        return array('html' => '', 'stats' => array('count' => 0));
    }
}

function kirb_handle_recent_compare_items_db($diamond_id, $user_id, $type, $catg) {
    global $wpdb;
    $table_name = $wpdb->prefix . "kirb_compare_recent_prods";
    $type_code = $type == 'compare' ? 0 : 1;

    $existing_record = $wpdb->get_row(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is internal
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}kirb_compare_recent_prods WHERE type = %d AND user_id = %d", $type_code, $user_id
        )
    );

    if (!$existing_record) {
        $prep_data = array(
            $catg => array($diamond_id)
        );
        $diamond_ids_json = wp_json_encode($prep_data);
        $wpdb->query(
            $wpdb->prepare(
                "INSERT INTO " . $wpdb->prefix . "kirb_compare_recent_prods (type, diamond_uid, user_id) VALUES (%d, %s, %d)",
                $type_code,
                $diamond_ids_json,
                $user_id
            )
        );
        return $prep_data;
    }else{
        $diamond_ids = json_decode($existing_record->diamond_uid, true);
        $current_catg_diamond_ids = array();

        if($type == 'recent') {
            $max_recent_items = 10;
            
            if(array_key_exists($catg, $diamond_ids)) {
                $current_catg_diamond_ids = $diamond_ids[$catg];
            }

            // Remove duplicate IDs if present
            $current_catg_diamond_ids = array_unique($current_catg_diamond_ids);

            // Remove the existing ID if it already exists
            $current_catg_diamond_ids = array_values(array_diff($current_catg_diamond_ids, [$diamond_id]));

            // Prepend the new ID to the beginning of the array
            array_unshift($current_catg_diamond_ids, $diamond_id);

            // Limit the array to the maximum recent items
            $current_catg_diamond_ids = array_slice($current_catg_diamond_ids, 0, $max_recent_items);

        }else{
            $current_catg_diamond_ids = array();
            if(array_key_exists($catg, $diamond_ids)) {
                $current_catg_diamond_ids = $diamond_ids[$catg];
            }
            
            // Compare logic works like, if the diamond is already in the compare list, remove it and max 4 items should be there
            if(in_array($diamond_id, $current_catg_diamond_ids)) {
                $current_catg_diamond_ids = array_values(array_diff($current_catg_diamond_ids, [$diamond_id]));
            }else{
                // Prepend the new ID to the beginning of the array
                array_unshift($current_catg_diamond_ids, $diamond_id);
            }
            
        }

        $diamond_ids[$catg] = $current_catg_diamond_ids;
        $diamond_ids_json = wp_json_encode($diamond_ids);

        $wpdb->query(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is internal
            $wpdb->prepare(
                "UPDATE {$wpdb->prefix}kirb_compare_recent_prods SET diamond_uid = %s WHERE user_id = %d AND type = %d",
                $diamond_ids_json,
                $user_id,
                $type_code
            )
        );

        return $diamond_ids;
    }
}

function kirb_prepare_rc_list($type, $user_id, $catg) {
    global $wpdb;
    $type_code = $type == 'compare' ? 0 : 1;
    $results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT diamond_uid FROM {$wpdb->prefix}kirb_compare_recent_prods WHERE type = %d AND user_id = %d",
            array($type_code,$user_id)
        ),
        ARRAY_A
    );

    if(!empty($results)) {
        $results = array_column($results, 'diamond_uid')[0];
        $diamond_uids = json_decode($results, true);
        if($diamond_uids && !empty($diamond_uids)) {            
            $current_catg_list = array();
            if(array_key_exists($catg, $diamond_uids)) {
                $current_catg_list = $diamond_uids[$catg];
            }
            return $current_catg_list;
        }
    }
    return false;
}

function kirb_get_diamond_uid_by_post_id($postId)
{
    global $wpdb;
    $result = $wpdb->get_results($wpdb->prepare("SELECT diamond_uid FROM ".$wpdb->prefix."kirb_diamonds_meta WHERE post_id = %s", $postId));
    
    if (count($result) > 0) {
        return $result[0]->diamond_uid;
    }
    return false;
}

function kirb_getByorDataForCurrentUser($uid = '') {
    global $wpdb;
    $user_id = kirb_getCurrentUserId();
    $byor_data = '';

    if(!empty($uid)) {
        $byor_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}kirb_byor WHERE uid = %s", $uid), ARRAY_A);
    }

    if(empty($uid) || !$byor_data) {
        $byor_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}kirb_byor WHERE user_id = %s", $user_id), ARRAY_A);
    }

    if(!empty($byor_data)) {
        $resp = array(
            'order' => $byor_data['ord'],
            'diamond_uid' => $byor_data['diamond_uid'],
            'diamond_type' => $byor_data['diamond_type'], // 0 = diamond, 1 = gemstone
            'ring_post_id' => $byor_data['ring_post_id'],
            'ring_variation_id' => $byor_data['ring_variation_id'],
            'ring_attributes' => $byor_data['ring_attributes'],
            'uid' => $byor_data['uid'],
            'setting_type' => $byor_data['setting_type'],
        );

        if(!empty($byor_data['diamond_uid']) && $byor_data['diamond_uid'] != '0') {
            $diamondData = kirb_getDiamondByUID($byor_data['diamond_uid']);
            if(!$diamondData['error']) {
                $resp['diamond'] = $diamondData['diamond'];
            }else{
                return false;
            }
        }
        if($byor_data['ring_post_id'] != 0) {
            $ringData = wc_get_product($byor_data['ring_post_id']);
            if($ringData) {
                $resp['ring_is_variable'] = $ringData->get_type() == "variable";
                if($ringData->get_type() == "variable") {
                    $ringData = wc_get_product($byor_data['ring_variation_id']);
                }
                $resp['ring'] = $ringData;
                $resp['ring_attributes'] = json_decode($byor_data['ring_attributes'], true);
            }else{
                $byor_data['ring_post_id'] = 0;
            }
        }
        return $resp;
    }
    return false;
}

function kirb_addProductToByor($product) {
    global $wpdb;

    if (!in_array($product['type'], array('diamond', 'ring'))) {
        return array('status' => 'fail', 'message' => 'Invalid product type!');
    }

    $user_id = kirb_getCurrentUserId(); // Get current user ID
    $byor_data = $wpdb->get_row($wpdb->prepare("SELECT id FROM {$wpdb->prefix}kirb_byor WHERE user_id = %s", $user_id), ARRAY_A);

    // 0 = diamond first, 1 = ring first
    $order = $product['type'] == 'diamond' ? 0 : 1;

    if (!$byor_data) {

        // Generate a unique ID for the BYOR
        $uid = md5(kirb_gen_uuidv4() . time());

        // Insert new byor data
        $wpdb->insert($wpdb->prefix . 'kirb_byor', 
            array(
                'uid' => $uid,
                'user_id' => $user_id, 
                'ring_post_id' => 0, 
                'ring_variation_id' => 0,
                'ring_attributes' => '',
                'diamond_uid' => '0',
                'diamond_type' => 0,
                'setting_type' => -1,
                'ord' => $order
            ), 
            array('%s', '%s', '%d', '%d', '%s', '%s', '%d', '%d', '%d')
        );
        $byor_id = $wpdb->insert_id;
    } else {
        $byor_id = $byor_data['id'];
    }

    if ($product['type'] == 'diamond') {
        $diamond_uid = $product['product_id'];
        $diamond_type = $product['diamond_type'] == 'diamond' ? 0 : 1;
        $wpdb->update($wpdb->prefix . 'kirb_byor', 
            array(
                'diamond_uid' => $diamond_uid, 
                'diamond_type' => $diamond_type
            ), 
            array('id' => $byor_id), 
            array('%s','%d'), 
            array('%d')
        );
        return array('status' => 'success', 'message' => 'Diamond added to BYOR!');
    } elseif ($product['type'] == 'ring') {
        $ring_id = $product['product_id'];
        $variation_id = $product['variation_id'];
        $wpdb->update($wpdb->prefix . 'kirb_byor', 
            array(
                'ring_post_id' => $ring_id,
                'ring_variation_id'=> $variation_id,
                'ring_attributes' => wp_json_encode($product['attributes']),
                'setting_type' => $product['setting_type']
            ), 
            array('id' => $byor_id), 
            array('%d', '%d', '%s', '%d'),
            array('%d')
        );
        return array('status' => 'success', 'message' => 'Ring added to BYOR!');
    }

    return array('status' => 'fail', 'message' => 'Something went wrong!');
}

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

function kirbGetMeta($key, $table_might_not_exists = false) {
    global $wpdb;
    if($table_might_not_exists) {
        // Build the table name
        $table_name = $wpdb->prefix . 'kirb_metadata';

        // Check if the table exists
        $table_exists = $wpdb->get_var(
            $wpdb->prepare("SHOW TABLES LIKE %s", $table_name)
        );

        // If the table doesn't exist, just return false (or handle differently)
        if (!$table_exists) {
            return false;
        }
    }
    
    $result = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}kirb_metadata WHERE meta_key = %s",
            $key
        ),
        ARRAY_A
    );
    if (count($result) > 0) {
        return $result[0]['meta_value'];
    }
    return false;
}

function kirbDeleteMeta($key) {
    global $wpdb;
    $wpdb->delete($wpdb->prefix . 'kirb_metadata', array('meta_key' => $key), array('%s'));
}

function kirb_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 kirb_register_plugin($permission = false) {
    $url = KIRB_ENDPOINT_URL . "/install-app";
    $shop_email = kirbGetMeta("_shop_email");
    $current_domain = '';
    if ( isset( $_SERVER['HTTP_HOST'] ) ) {
        $current_domain = sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) );
    }
    
    if(!$shop_email) {
        if($permission) {
            $shop_email = get_option('admin_email');
        }else{
            $shop_email = "appuser@keyideasjewelry.com";
        }
    }

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

    $shop_name = kirbGetMeta("_shop_name");
    if(!$shop_name) {
        $shop_name = explode("@", $shop_email)[0] . "-kirb-".kirb_gen_uuidv4()."-shop";
    }

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

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if($data['type'] == 'success') {
        kirbAddMeta("_store_token", $data['store_token']);
        kirbAddMeta("_shop_name", $data['storeUrl']);
        kirbAddMeta("_shop_email", $shop_email);
    }
    
    kirbAddMeta('_is_plugin_active', 'true');
}

add_action('admin_notices', 'kirb_deactivation_admin_notice');
function kirb_deactivation_admin_notice() {
    if ($message = get_transient('kirb_deactivation_message')) {
        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html($message) . '</p></div>';
        delete_transient('kirb_deactivation_message');
    }
}

function kirb_getRecommendedDiamonds($diamond_uid){
    $store_token = kirbGetMeta('_store_token');
    if(!$store_token || ($store_token && empty($store_token))) {
        return false;
    }
    $currency = get_woocommerce_currency();
    $url = KIRB_ENDPOINT_URL . '/get-recommended?productId='. $diamond_uid . '&currency=' . $currency;
    $data = kirb_downloadAndCacheFile($url, "kirb-recommended-cache-$diamond_uid.json", $store_token);
    if($data && isset($data['similarProducts'])) {
        return $data;
    }
    return false;
}

// create ringsize data and return array
function kirb_getRingSizeList() {
    $regional_data = kirbGetMeta("_regional_data");
    $ring_size_country = "r1";
    $current_region = kirb_determine_locale();
    if($regional_data) {
        $regional_data = json_decode($regional_data, true);
        if(isset($regional_data[$current_region])) {
            $ring_size_country = $regional_data[$current_region]['ring_size'];
        }
    }

    $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;
        $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 kirb_getDiamondListingHeaders($type, $catg = '') {
    if ($type == 'rc') {
        $output = "
        <th class='shape-heading'><span>Shape</span></th>
        <th class='view360-heading'></th>
        <th  >" . esc_html('Price') . "</th>
        <th class = 'mobile-view'  >" . esc_html('Shape') . "</th>           
        <th  class = ''> " . esc_html('Carat') . "</th>
        <th  class = 'mobile-view'> " . esc_html('Color') . "</th>";
        if ($catg != 'GEMSTONE' && $catg != 'COLORED DIAMONDS') {

            $output .= "  <th  class = 'mobile-view'> " . esc_html('Cut') . "</th>";
        }
        if ($catg != 'GEMSTONE') {
            $output .= " <th  class = 'mobile-view'> " . esc_html('Clarity') . "</th>";
        }
        if ($catg == 'GEMSTONE') {
            $output .= "<th  class = ''>" . esc_html('Type') . "</th>";
        }
        if ($catg == 'COLORED DIAMONDS') {
            $output .= "<th  class = ''>" . esc_html('Intensity') . "</th>";
        }

        $output .= "<th  class = 'mobile-view'> " . esc_html('Lab') . "</th>";
        $output .= "<th class='compare-heading'>" . esc_html('Compare') . "</th>";
        $output .= "<th></th>";

        return $output;
    } else {
        $html = "
            <th class='shape-heading'><span>Shape</span></th>
            <th class='view360-heading'></th>
            <th class='compare-heading'>".esc_html('Compare')."</th>
            <th>".esc_html('Price')."</th>
            <th>".esc_html('Carat')."</th>
            <th>".esc_html('Color')."</th>
        ";
        $html = "
            <th class='shape-heading'><span>Shape</span></th>
            <th class='view360-heading'></th>
            <th>".esc_html('Price')."</th>
            <th  class = 'mobile-view'>".esc_html('Shape')."</th>
            <th>".esc_html('Carat')."</th>
            <th  class = 'mobile-view'>".esc_html('Color')."</th>
        ";
        if($catg == 'GEMSTONE') {
            $html .= "<th  class = ''>".esc_html('Type')."</th><th  class = 'mobile-view'>".esc_html('Lab')."</th><th class='compare-heading'>".esc_html('Compare')."</th>";

        }else{
            $type = ($catg == 'COLORED DIAMONDS') ? esc_html('Intensity'): esc_html('Cut');
            $html .= "
                <th  class = 'mobile-view'>".esc_html('Clarity')."</th>";
                if($catg == 'COLORED DIAMONDS'){
                    $html .= " <th  class = ''>". esc_html('Intensity')."</th>";
               }
               else{
                   $html .= " <th  class = 'mobile-view'>".esc_html('Cut')."</th>";
               }
              
               $html .= "<th  class = 'mobile-view'>".esc_html('Lab')."</th>";
               $html .= "<th class='compare-heading'>".esc_html('Compare')."</th>";
        }
        $html .= "
            <th></th>
        ";
        return $html;
    }
}

function kirb_getDeliveryDateByDiamondVendor($settingId, $kirb_filters_data) {
    $ship_days = 15;
    foreach($kirb_filters_data['shippingDay'] as $setting) {
        if($setting['SettingId'] == $settingId) {
            $ship_days = $setting['day'];
            break;
        }
    }

    $date = gmdate('Y-m-d', strtotime("+$ship_days days"));
    // $day = gmdate('l', strtotime($date));
    // if($day == 'Sunday') {
    //     $date = gmdate('Y-m-d', strtotime("+1 days", strtotime($date)));
    // }elseif($day == 'Saturday') {
    //     $date = gmdate('Y-m-d', strtotime("+2 days", strtotime($date)));
    // }
    return gmdate('l, F j', strtotime($date));
}

function kirb_isValidMongoDBObjectId($id) {
    if($id) {
        if (strlen($id) !== 24) {
            return false;
        }
        if (!ctype_xdigit($id)) {
            return false;
        }
        return true;
    }
    return false;
}

function kirb_get_user_defined_localization() {
    $localization_cache_key = "kirb-ud-local-cache";
    $cached_localization = kirb_get_cache_db($localization_cache_key);
    if ($cached_localization !== false) {
        return $cached_localization;
    }
    $user_defined_localization = kirb_file_get_contents(wp_get_upload_dir()['baseurl'] . '/kirb-user-defined-localization.json');
    $user_defined_localization = json_decode($user_defined_localization, true);
    kirb_set_cache_db($localization_cache_key, $user_defined_localization, 12 * HOUR_IN_SECONDS);
    return $user_defined_localization;
}

function kirb_get_string($group, $key, $user_defined_localization = null) {
    if($user_defined_localization == null) {
        $user_defined_localization = kirb_get_user_defined_localization();
    }
    $lang = kirb_determine_locale();
    if(isset($user_defined_localization[$group]) && isset($user_defined_localization[$group][$key])) {
        return $user_defined_localization[$group][$key][$lang];
    }
    return "";
}

function kirb_get_metal_name_by_variation_id($variation_id, $formatted = true) {
    // Early return if no variation_id
    if (!$variation_id) {
        return '';
    }

    $variation = new WC_Product_Variation($variation_id);
    $attributes = $variation->get_attributes();
    
    // If no attributes found, return empty
    if (empty($attributes)) {
        return '';
    }

    $config_metal_slug = kirb_get_config('setting_metal_slug');
    
    // Format value function to avoid code duplication
    $format_value = function($value) use ($formatted) {
        if (!$formatted) {
            return $value;
        }
        
        return ucwords(str_replace(
            ['-', '_', '18k', '14k'],
            [' ', ' ', '18K', '14K'],
            $value
        ));
    };

    // If config slug exists, check only that attribute
    if ($config_metal_slug && isset($attributes[$config_metal_slug])) {
        return $format_value($attributes[$config_metal_slug]);
    }

    // If no config slug, check for metal-related attributes
    if (!$config_metal_slug) {
        $metal_keywords = ['metal', 'color', 'colour', 'alloy'];
        foreach ($attributes as $key => $value) {
            foreach ($metal_keywords as $keyword) {
                if (str_contains($key, $keyword)) {
                    return $format_value($value);
                }
            }
        }
    }
    return "";
}

function kirb_price_roundoff($price, $config) {
    if($config != null) {
        $round_off_by = kirb_get_config('price_roundoff_by', $config);
        if($round_off_by) {
            $round_off_by = intval($round_off_by);
            return ceil(intval($price) / $round_off_by) * $round_off_by;
        }
    }
    return intval($price);
}

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


function kirb_string_split_translate($str, $lookup_table) {
    $orig_str = $str;
    $str = preg_replace(['/[^A-Za-z]/', '/\s+/'], [' ', ' '], $str);
    $str = trim($str);
    $words = explode(' ', $str);
    foreach($words as $word) {
        $translatedWord = esc_html($lookup_table[$word] ?? $word);
        if($translatedWord !== $word) {
            $orig_str = str_replace($word, $translatedWord, $orig_str);
        }
    }
    return $orig_str;
}

function kirb_string_reverse_translate($str) {
    $str = strtolower($str);
    $orig_str = $str;
    $str = preg_replace(['/[^A-Za-z]/', '/\s+/'], [' ', ' '], $str);
    $str = trim($str);
    $words = explode(' ', $str);

    $locale = kirb_determine_locale();
    $json_file_local = KIRB_BASE_DIR . "languages/{$locale}.json";
    $json_file_path = KIRB_PLUGIN_DIR . "/languages/{$locale}.json";
    if(file_exists($json_file_local)) {
        $translations = json_decode(kirb_file_get_contents($json_file_path), true);
        $keys = array_map('strtolower', array_keys($translations));
        $values = array_map('strtolower', array_values($translations));
        $translations = array_combine($values, $keys);
    }

    foreach($words as $word) {
        if(isset($translations[$word])) {
            $orig_str = str_replace($word, $translations[$word], $orig_str);
        }
    }
    return $orig_str;
}

function kirb_clear_cache() {
    global $wpdb;
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- static table name
    $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}kirb_cache");
}

function kirb_auto_clear_cache() {
    $server_feed_updated = kirb_get_feed_updated_timstamp();
    $last_feed_update = kirbGetMeta('_last_feed_update');
    if(!$last_feed_update) {
        kirb_clear_cache();
        kirbAddMeta('_last_feed_update', $server_feed_updated);
        return;
    }else{
        if($server_feed_updated) {
            if($server_feed_updated > $last_feed_update) {
                kirb_clear_cache();
                kirbAddMeta('_last_feed_update', $server_feed_updated);
            }
        }
    }
}

function kirb_get_feed_updated_timstamp() {
    $store_token = kirbGetMeta('_store_token');
    if(!$store_token || ($store_token && empty($store_token))) {
        return false;
    }
    $data = kirb_downloadAndCacheFile(KIRB_ENDPOINT_URL . '/get-sold-out', 'kirb-last-updated-cache.json', $store_token, true);
    if(isset($data['cache']['updated_at'])) {
        $date = new DateTime($data['cache']['updated_at']);
        $timestamp = $date->getTimestamp();
        return $timestamp;
    }
    return false;
}

function kirb_table_exists($table_name) {
    global $wpdb;
    $table_exists = $wpdb->get_var($wpdb->prepare(
        "SHOW TABLES LIKE %s",
        $table_name
    ));
    return ($table_exists === $table_name);
}

// function kirb_migrate_table($table_arr) {
//     foreach($table_arr as $table) {
//         $old_table = str_replace("kirb_","wcrb_",$table);
//         global $wpdb;
//         if(kirb_table_exists($old_table) && !kirb_table_exists($table)) {
//             $wpdb->query("RENAME TABLE $old_table TO $table");
//         }
//         if(kirb_table_exists($old_table)) {
//             $wpdb->query("DROP TABLE $old_table");
//         }
//     }
// }

function kirb_get_page_parent_slug($slug) {
    $parent_catgs = array();
    $product_cat = get_term_by('slug', $slug, 'product_cat');
    array_push($parent_catgs, $product_cat->slug);
    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 kirb_get_parent_slug($product) {
    $parent_catgs = array();
    if($product) {
        $product_cat_ids = $product->get_category_ids();
        if (!empty($product_cat_ids)) {
            foreach($product_cat_ids as $cat_id) {
                $product_cat = get_term_by('id', $cat_id, 'product_cat');
                array_push($parent_catgs, $product_cat->slug);
                // 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 array_unique($parent_catgs);
}

function kirb_sideload_css($page = false) {
    $ver = KIRB_VERSION_CONTROL['sideload_styles_css'];
    
    $kirb_upload_dir = wp_get_upload_dir();
    $kirb_sideload_base = $kirb_upload_dir['baseurl'] . '/kirb-sideload-files';

    $css_files = array(
        $kirb_sideload_base . '/style.css' => $ver,
    );
    
    if($page) {
        // Page level css files support
        $page_css_files = array(
            'setting' => array(
                $kirb_sideload_base . '/setting-style.css' => $ver,
            ),
            'listing' => array(
                $kirb_sideload_base . '/listing-style.css' => $ver,
            ),
            'detail' => array(
                $kirb_sideload_base . '/detail-style.css' => $ver,
            ),
        );

        // merge with page level css files
        $css_files = array_merge($css_files, $page_css_files[$page]);
    }
    // Possible dependencies
    $deps = array('kirb-custom-plugin-style', 'kirb-custom-eng-script','kirb-byor-strip-style','kirb-custom-style');
    $final_deps = array();
    foreach ($deps as $dep) {
        if(wp_style_is($dep, 'registered') || wp_style_is($dep, 'enqueued')) {
            $final_deps[] = $dep;
        }
    }
    foreach ($css_files as $file => $version) {
        $uid = str_replace(".","-",basename($file));
        if((!wp_style_is("kirb-custom-sideload-style-$uid", 'registered') && !wp_style_is("kirb-custom-sideload-style-$uid", 'enqueued')) && file_exists(KIRB_BASE_DIR . 'sideload-files/'.basename($file))) {
            wp_enqueue_style("kirb-custom-sideload-style-$uid", $file,  $final_deps, $version, 'all');
        }
    }
}

function kirb_set_completed_tab($tab, $bool) {
    global $kirb_active_tab_config;
    if($kirb_active_tab_config) {
        $kirb_active_tab_config[$tab]['completed'] = $bool;
    }
    $temp_kirb_active_tab_config = json_decode(kirbGetMeta('_admin_tab_config'), true);
    $temp_kirb_active_tab_config[$tab]['completed'] = $bool;
    kirbAddMeta('_admin_tab_config', wp_json_encode($temp_kirb_active_tab_config));
    unset($temp_kirb_active_tab_config); // Free memory
}

function kirb_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 = 'other';
    }
    return $locale;
}

function kirb_get_config_file() {
    $cache_key = 'kirb_cached_config';

    // Try to get cached config from our custom cache table
    $cached_config = kirb_get_cache_db($cache_key);

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

    $upload_dir = wp_get_upload_dir();
    $config_file_name = 'kirb-site-config.json';
    $config_base_file = $upload_dir['basedir'] . '/' . $config_file_name;
    $config_file = $upload_dir['baseurl'] . '/' . $config_file_name;

    if (file_exists($config_base_file)) {
        $config_content = kirb_file_get_contents($config_file);
        if ($config_content) {
            $config = json_decode($config_content, true);

            if (is_array($config)) {
                // 12 hours
                kirb_set_cache_db($cache_key, $config, 12 * HOUR_IN_SECONDS);
                return $config;
            }
        }
    }

    return false;
}

function kirb_get_config($key, $config = null) {
    if($config == null) {
        $config = kirb_get_config_file();
    }
    if($config && isset($config[$key]) && !empty($config[$key])) {
        return $config[$key];
    }
    return false;
}

function kirb_syncData($oldData, $newData) {
    // First, remove keys from old data that are not in new data
    foreach ($oldData as $key => $value) {
        if (!array_key_exists($key, $newData)) {
            unset($oldData[$key]);
        }
    }

    // Then, add or update keys from the new data
    foreach ($newData as $key => $value) {
        if (is_array($value)) {
            // If the key exists in old data and is an array, sync recursively
            if (isset($oldData[$key]) && is_array($oldData[$key])) {
                $oldData[$key] = kirb_syncData($oldData[$key], $value);
            } else {
                // Add the new key-value pair if not present
                if (!isset($oldData[$key])) {
                    $oldData[$key] = $value;
                }
            }
        } else {
            // Add the new key-value pair if not present
            if (!isset($oldData[$key])) {
                $oldData[$key] = $value;
            }
        }
    }
    return $oldData;
}
function kirb_sanitize_svg_output($svg) {
    // Define allowed tags and attributes for SVG
    $allowed_tags = [
        'svg' => [
            'xmlns' => true,
            'xmlns:xlink' => true,
            'version' => true,
            'class' => true,
            'x' => true,
            'y' => true,
            'viewbox' => true,
            'enable-background' => true,
            'xml:space' => true,
            'style' => true,
        ],
        'g' => [],
        'line' => [
            'fill' => true,
            'stroke' => true,
            'stroke-width' => true,
            'stroke-miterlimit' => true,
            'x1' => true,
            'y1' => true,
            'x2' => true,
            'y2' => true,
        ],
        'rect' => [
            'x' => true,
            'y' => true,
            'fill' => true,
            'width' => true,
            'height' => true,
        ],
        'path' => [
            'fill' => true,
            'stroke' => true,
            'stroke-width' => true,
            'stroke-linejoin' => true,
            'd' => true,
        ],
        'polygon' => [
            'fill' => true,
            'stroke' => true,
            'stroke-width' => true,
            'stroke-linejoin' => true,
            'points' => true,
        ],
        'text' => [
            'transform' => true,
            'fill' => true,
            'font-family' => true,
            'font-size' => true,
            'class' => true,
        ],
        'tspan' => [
            'x' => true,
            'y' => true,
            'fill' => true,
            'font-family' => true,
            'font-size' => true,
            'class' => true,
        ],
    ];

    // Sanitize the SVG
    return wp_kses($svg, $allowed_tags, ['http','https']);
}

function kirb_sanitize_listing_items($html) {
    $allowed_html = wp_kses_allowed_html('post');
    $tags_to_modify = array('div', 'td', 'button', 'a', 'span');
    foreach ($tags_to_modify as $tag) {
        if (!isset($allowed_html[$tag])) {
            $allowed_html[$tag] = array(); // Initialize if the tag is not already defined
        }
        $allowed_html[$tag]['onclick'] = true; // Add onclick attribute
    }
    return wp_kses($html, $allowed_html);
}


function kirb_log($content) {
    $log_file = KIRB_BASE_DIR . 'kirb-log.txt';
    $content = wp_date('Y-m-d H:i:s', current_time('timestamp')) . ' - ' . $content . PHP_EOL;
    file_put_contents($log_file, $content, FILE_APPEND);
}

function kirb_get_user_id_by_byor_uid($uid) {
    global $wpdb;
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is internal constant
    $user_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->prefix}kirb_byor WHERE uid = %s", $uid));
    return $user_id;
}

function kirb_is_valid_MD5($md5) {
    return preg_match('/^[a-f0-9]{32}$/', $md5);
}

function kirb_post_stats_update($diamond_uid, $type) {
    $valid_types = array('add_to_cart', 'order', 'byor');
    if(!in_array($type, $valid_types) || empty($diamond_uid)) {
        return false;
    }

    $url = KIRB_ENDPOINT_URL . "/stats-log";

    $shop_name = kirbGetMeta("_shop_name");
    
    if (!$shop_name) {
        return false;
    }

    $store_token = kirbGetMeta('_store_token');
    if(!$store_token || ($store_token && empty($store_token))) {
        return false;
    }

    $args = array(
        'method'  => 'POST',
        'headers' => array(
            'Content-Type' => 'application/json',
            'shop'         => $shop_name,
            'token'        => $store_token,
        ),
        'timeout' => 20,
        'body'    => wp_json_encode(array(
            'type'       => $type,
            'platform'   => 'wordpress',
            'pid'        => $diamond_uid,
            'session_id' => session_id(),
        )),
    );

    $response = wp_remote_post($url, $args);
    if (is_wp_error($response)) {
        return false;
    }
    $code = wp_remote_retrieve_response_code($response);
    return (int)$code === 200;
}

function kirb_get_addon_value($key) {
    $data = kirbGetMeta('_setting_addon_data');
    if($data) {
        $data = json_decode($data, true);
        if(isset($data[$key])) {
            return $data[$key];
        }
    }
    return false;
}

function kirb_copy_dir($source, $destination) {
    // If source is not a directory, bail
    if (!is_dir($source)) {
        return false;
    }

    // Create the destination folder if it doesn't exist
    if (!file_exists($destination)) {
        // Use WordPress helper for creating directories
        if (!wp_mkdir_p($destination)) {
            return false;
        }
    }

    // Loop through the folder contents
    $items = scandir($source);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;

        $src = $source . DIRECTORY_SEPARATOR . $item;
        $dest = $destination . DIRECTORY_SEPARATOR . $item;

        if (is_dir($src)) {
            // Recursive call for subdirectories
            kirb_copy_dir($src, $dest);
        } else {
            copy($src, $dest);
        }
    }

    return true;
}

function kirb_set_pages_status($status) {
    global $wpdb;

    // Fetch stored page IDs from wp_kirb_metadata
    $page_ids_json = kirbGetMeta('_page_ids');
    if (!$page_ids_json) {
        return;
    }

    $page_ids_array = json_decode($page_ids_json, true);
    if (!is_array($page_ids_array)) {
        return;
    }

    // Extract page IDs from the array
    $page_ids = array_values($page_ids_array);

    if (!empty($page_ids)) {
        $ids = array_map('absint', $page_ids);
        $placeholders = implode(',', array_fill(0, count($ids), '%d'));
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID IN ($placeholders)",
                array_merge( array( $status ), $ids )
            )
        );
    }
}

/**
 * Core utility function to handle product actions.
 */
function kirb_handle_products_by_meta($meta_key, $meta_value, $post_status , $action) {
    global $wpdb;

    $product_ids = $wpdb->get_col($wpdb->prepare("
        SELECT p.ID
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE p.post_type = 'product'
          AND p.post_status = %s
          AND pm.meta_key = %s
          AND pm.meta_value = %s
    ", $post_status, $meta_key, $meta_value));

    foreach ($product_ids as $product_id) {
        switch ($action) {
            case 'delete':
                kirb_delete_product_with_images($product_id, true);
                break;

            case 'draft':
                wp_update_post([
                    'ID' => (int) $product_id,
                    'post_status' => 'draft',
                ]);
                update_post_meta($product_id, '_kirb_drafted_by_plugin', 'yes');
                break;

            case 'publish':
                wp_update_post([
                    'ID' => (int) $product_id,
                    'post_status' => 'publish',
                ]);
                delete_post_meta($product_id, '_kirb_drafted_by_plugin');
                break;
        }
    }
}

function kirb_get_demo_products($importType) {
    $data = kirb_get_cache_db($importType . '_keyideas_products');
    if ($data !== false) {
        return $data;
    }

    $vendor_token = "jIHwunxua7hpxCtU3s1P7sVtmAcXvMa";

    if($importType == "wedding"){
        $vendor_token = "yAX7MT96T85HW6OWB4snfLmg2xwI5A";
    }

    $url = "https://keyideasglobal.com/qa/diamondserver/wp-json/products/v1/list";

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 30,
        'headers' => [
            'token' => 'KkCui1WY3jFlcpgqIVkQ6B0JwzNxIs'
        ],
        'body' => [
            "vendor_token" => $vendor_token
        ],
    ));

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if ($data !== null) {
        kirb_set_cache_db($importType . '_keyideas_products', $data, KIRB_CACHE_DATA_TIME * 60);
    }

    return $data;
}

function kirb_delete_product_with_images( $product_id, $delete_post ) {
    // Delete featured image of main product
    $thumbnail_id = get_post_thumbnail_id( $product_id );
    if ( $thumbnail_id ) {
        wp_delete_attachment( $thumbnail_id, true );
    }

    // Delete gallery images (main product)
    $product_gallery_ids = get_post_meta( $product_id, '_product_image_gallery', true );
    if ( $product_gallery_ids ) {
        $product_gallery_ids = explode( ',', $product_gallery_ids );
        foreach ( $product_gallery_ids as $attachment_id ) {
            $attachment_id = (int) $attachment_id;
            wp_delete_attachment( $attachment_id, true );
        }
    }

    // Delete variations and their images
    $variations = get_children([
        'post_parent' => $product_id,
        'post_type'   => 'product_variation',
        'fields'      => 'ids'
    ]);

    foreach ( $variations as $variation_id ) {
        // Variation featured image
        $variation_thumb_id = get_post_thumbnail_id( $variation_id );
        if ( $variation_thumb_id ) {
            wp_delete_attachment( $variation_thumb_id, true );
        }

        // Variation default gallery (_product_image_gallery)
        $variation_gallery_ids = get_post_meta( $variation_id, '_product_image_gallery', true );
        if ( $variation_gallery_ids ) {
            $variation_gallery_ids = explode( ',', $variation_gallery_ids );
            foreach ( $variation_gallery_ids as $attachment_id ) {
                $attachment_id = (int) $attachment_id;
                wp_delete_attachment( $attachment_id, true );
            }
        }

        // Variation custom gallery (woo_variation_gallery_images)
        $variation_gallery_ids_custom = get_post_meta( $variation_id, 'woo_variation_gallery_images', true );
        if ( $variation_gallery_ids_custom ) {
            if ( is_array($variation_gallery_ids_custom) ) {
                $ids_to_delete = $variation_gallery_ids_custom;
            } else {
                $ids_to_delete = explode(',', $variation_gallery_ids_custom);
            }
            foreach ( $ids_to_delete as $attachment_id ) {
                $attachment_id = (int) $attachment_id;
                wp_delete_attachment( $attachment_id, true );
            }
        }

    }

    // delete the main product
    if ( $delete_post ) {
        wp_delete_post( $product_id, true );
    }
}

function kirb_readable_text_color(string $hex) {
    // Normalize input: strip '#', keep only hex chars
    $h = preg_replace('/[^0-9a-fA-F]/', '', ltrim($hex, '#'));

    // Expand short forms (#RGB or #RGBA) to #RRGGBB[AA]
    if (strlen($h) === 3 || strlen($h) === 4) {
        $h = preg_replace('/(.)/u', '$1$1', $h); // duplicate each nibble
    }

    // If 8 digits, ignore alpha (first 6 are RGB, last 2 alpha)
    if (strlen($h) >= 6) {
        $h = substr($h, 0, 6);
    } else {
        // Not enough data → safe default
        return '#000000';
    }

    $r = hexdec(substr($h, 0, 2));
    $g = hexdec(substr($h, 2, 2));
    $b = hexdec(substr($h, 4, 2));

    // Convert sRGB to linear
    $linear = function (float $c): float {
        $c = $c / 255;
        return ($c <= 0.03928) ? ($c / 12.92) : pow(($c + 0.055) / 1.055, 2.4);
    };

    $R = $linear($r);
    $G = $linear($g);
    $B = $linear($b);

    // Relative luminance per WCAG
    $L = 0.2126 * $R + 0.7152 * $G + 0.0722 * $B;

    // Contrast ratios against white and black
    $contrastWhite = (1.0 + 0.05) / ($L + 0.05);
    $contrastBlack = ($L + 0.05) / 0.05;

    // Choose the higher contrast
    return ($contrastWhite >= $contrastBlack) ? '#ffffff' : '#000000';
}

function kirbHexToRgb($hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    $shorthandRegex = '/^#?([a-f\d])([a-f\d])([a-f\d])$/i';
    $hex = preg_replace($shorthandRegex, '$1$1$2$2$3$3', $hex);

    $result = [];
    if (preg_match('/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i', $hex, $matches)) {
        $result[] = hexdec($matches[1]);
        $result[] = hexdec($matches[2]);
        $result[] = hexdec($matches[3]);
    }
    return $result;
}

function kirbLoadByorStrip() {
    $include_path = "";
    if(KIRB_BYOR_STRIP_THEME == 'arrow-step') {
        $include_path = WP_CONTENT_DIR . "/kirb-ui-components/byor-view-strip-".KIRB_BYOR_STRIP_THEME.".php";
        if(!file_exists($include_path)) {
            $include_path = KIRB_BASE_DIR . "/ui/byor-view-strip-circle-step.php";
        }
    }else{
        $include_path = KIRB_BASE_DIR . "/ui/byor-view-strip-circle-step.php";
    }
    include($include_path);
}

/* phpcs:enable */
