<?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 */

// AJAX action for loading more products
add_action('wp_ajax_kirb_load_more_prods', 'kirb_load_prods');
add_action('wp_ajax_nopriv_kirb_load_more_prods', 'kirb_load_prods');

// AJAX action for filtering products
add_action('wp_ajax_kirb_filter_products', 'kirb_load_prods');
add_action('wp_ajax_nopriv_kirb_filter_products', 'kirb_load_prods');

function kirb_load_prods() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $uri_segments = array();
        $parameterKeys = kirb_get_valid_filters_keys();
        $catg = isset($_GET['catg']) ? sanitize_text_field(wp_unslash($_GET['catg'])) : '';
        foreach ($parameterKeys as $key) {
            if (isset($_GET[$key])) {
                $uri_segments[$key] = sanitize_text_field(wp_unslash($_GET[$key]));
            }
        }
        global $kirb_filters_data;
        if(!$kirb_filters_data) {
            $kirb_filters_data = kirb_get_filters_data('kirb_load_prods');
        }
        $filter_options = array();
        foreach($kirb_filters_data['filterdata'] as $filter) {
            if($filter['category'] == $catg) {
                $filter_options = $filter;
                break;
            }
        }

        $init_fiter_shapes = array_map('strtolower',array_column($filter_options['shape'], 'name'));

        // Shape exclusive check
        $force_zero = false;
        if(!empty($uri_segments['shape']) && !in_array(strtolower($uri_segments['shape']), $init_fiter_shapes)) {
            $force_zero = true;
        }

        $filters = array(
            'category' => $catg,
            'page' => isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '',
            'filters_uri' => kirb_parse_filters_uri($uri_segments),
            'search' => isset($_GET['search']) ? sanitize_text_field(wp_unslash($_GET['search'])) : '',
            'force_zero' => $force_zero
        );
        $resp = kirb_prepare_diamond_listing($filters);
        if(isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) == '1') {
            $resp['list_html'] = kirb_diamond_listing_wrapper_code(intval($resp['stats']['count']) == 0, $catg, $resp['list_html']);
        }
        wp_send_json($resp);
    }
}

// kirb_load_compare_prods
add_action('wp_ajax_kirb_load_compare_prods', 'kirb_load_custom_prods');
add_action('wp_ajax_nopriv_kirb_load_compare_prods', 'kirb_load_custom_prods');

//kirb_load_recent
add_action('wp_ajax_kirb_load_recent_prods', 'kirb_load_custom_prods');
add_action('wp_ajax_nopriv_kirb_load_recent_prods', 'kirb_load_custom_prods');



function kirb_load_custom_prods() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $products = isset($_GET['products']) ? sanitize_text_field(wp_unslash($_GET['products'])) : '';
        $type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';

        if(!empty($products)) {
            $products = explode(",", $products);
        }
        
        wp_send_json(kirb_fetch_rc_prods($products, $type));
    }
}

// kirb_add_to_byor

add_action('wp_ajax_kirb_add_to_byor', 'kirb_add_to_byor');
add_action('wp_ajax_nopriv_kirb_add_to_byor', 'kirb_add_to_byor');

function kirb_add_to_byor() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $config = kirb_get_config_file();


        $product_id = isset($_GET['product_id']) ? sanitize_text_field(wp_unslash($_GET['product_id'])) : '';
        $type = (isset($_GET['type']) && sanitize_text_field(wp_unslash($_GET['type'])) == 'diamond') ? 'diamond' : 'ring'; // request forgery safety
        $variation_id = isset($_GET['variation_id']) ? sanitize_text_field(wp_unslash($_GET['variation_id'])) : 0;
        $diamond_type = isset($_GET['diamond_type']) ? sanitize_text_field(wp_unslash($_GET['diamond_type'])) : '';
        $ring_attributes = isset($_GET['attributes']) ? json_decode(stripslashes(sanitize_textarea_field(wp_unslash($_GET['attributes']))), true) : array();
        $diamond_redirect_to = isset($_GET['diamond_redirect']) ? sanitize_text_field(wp_unslash($_GET['diamond_redirect'])) : '';
        
        $setting_type_code = 0;

        $product = array(
            'product_id' => $product_id,
            'variation_id' => $variation_id,
            'diamond_type' => $diamond_type,
            'type' => $type,
            'attributes' => $ring_attributes,
            'setting_type' => $setting_type_code
        );

        kirb_addProductToByor($product);

        $redirect_url = "";
        $byor_data = kirb_getByorDataForCurrentUser();
        $isReviewRedirect = $byor_data && !empty($byor_data['diamond_uid']) && $byor_data['diamond_uid'] != '0' && $byor_data['ring_post_id'] != 0 && isset($byor_data['ring']) && $byor_data['ring'];
        $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);

        if ($isReviewRedirect) {
            $redirect_url = kirb_getPageUrlById($kirb_page_ids['byor-review']) . '/' .$byor_data['uid']; // review page
        } else if ($type == 'diamond') {
            $redirect_url = get_term_link(get_term_by('slug',kirbGetMeta('_setting_ring_setting_catg'), 'product_cat')); // setting page
            $dynamic_shape_query =  kirb_get_config("byor_redirect_dynamic_setting_shape_query_slug");
            if($dynamic_shape_query) {
                $diamond_shape = $byor_data['diamond']['shape'];
                if($diamond_shape) {
                    // $diamond_shape = "shape_" . $diamond_shape; // prefix for value
                    $redirect_url = str_ends_with($redirect_url, '/') ? $redirect_url : $redirect_url . '/';
                    $redirect_url .= '?' . $dynamic_shape_query . '=' . strtolower(str_replace(" ","_",$diamond_shape));
                }
            }
        } else {
            $catg = "";
            if(isset($_GET['catg']) && !empty($_GET['catg'])) {
                $catg_sanitized = sanitize_text_field(wp_unslash($_GET['catg']));
                $redirect_url = kirb_getPageUrlById($kirb_page_ids[KIRB_ALL_PAGES_MAP[$catg_sanitized]]); // diamond page
                $catg = KIRB_ALL_PAGES_MAP[$catg_sanitized];
            }else{
                $redirect_url = kirb_getPageUrlById($kirb_page_ids[KIRB_ALL_PAGES_MAP['loose-diamonds']]); // diamond page
                $catg = 'loose-diamonds';
            }

            $preset_filters = kirb_get_config('catg_filters_preset', $config);
            if($preset_filters && isset($preset_filters[$catg]) && !empty($preset_filters[$catg])) {
                if(isset($preset_filters[$catg]['shape'])) {
                    $shape_slug_config = kirb_get_config("listing_shape_slugs", $config);
                    if($shape_slug_config) {
                        foreach($shape_slug_config as $shape_slug => $shape_name) {
                            if($shape_name == $preset_filters[$catg]['shape']) {
                                $redirect_url = str_ends_with($redirect_url, '/') ? $redirect_url . $shape_slug . '/' : $redirect_url . '/' . $shape_slug . '/';
                                unset($preset_filters[$catg]['shape']);
                                break;
                            }
                        }
                    }
                }
                $redirect_url .= '?' . kirb_parse_filters_uri($preset_filters[$catg]);
            } else if($type == 'ring') {
                $shape_slug_config = kirb_get_config("byor_redirect_dynamic_shape_slug", $config);

                if($shape_slug_config) {
                    if($ring_attributes && isset($ring_attributes['attribute_'.$shape_slug_config])) {
                        $shape = $ring_attributes['attribute_'.$shape_slug_config];
                        if($shape) {
                            $redirect_url = str_ends_with($redirect_url, '/') ? $redirect_url . $shape . '/' : $redirect_url . '/' . $shape . '/';
                        }
                    }
                }
            }
        }
        if ($type == 'diamond') {
            kirb_post_stats_update($product_id, 'byor');
        }
        wp_send_json(array('status' => 'success', 'redirect_url' => $redirect_url));
    }
}

add_action('wp_ajax_kirb_handle_rc_prods', 'kirb_handle_rc_prods');
add_action('wp_ajax_nopriv_kirb_handle_rc_prods', 'kirb_handle_rc_prods');

function kirb_handle_rc_prods() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $user_id = kirb_getCurrentUserId();
        $diamond_id = isset($_GET['prod_id']) ? sanitize_text_field(wp_unslash($_GET['prod_id'])) : '';
        $type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';
        $catg = isset($_GET['catg']) ? sanitize_text_field(wp_unslash($_GET['catg'])) : "";

        $rc_result = array();
        
        $rc_result = kirb_handle_recent_compare_items_db($diamond_id, $user_id, $type, $catg);

        if(array_key_exists($catg, $rc_result)) {
            $rc_result = $rc_result[$catg];
        }

        if ($rc_result) {
            wp_send_json(
                array(
                    'prod_id_list' => $rc_result,
                    'result' => kirb_fetch_rc_prods($rc_result, $type)
                )
            );
        } else {
            wp_send_json(
                array(
                    'prod_id_list' => [],
                    'result' => array(
                        'html' => '',
                        'stats' => array('count' => 0)
                    )
                )
            );
        }
    }
}
add_action('wp_ajax_kirb_fetch_rc_items', 'kirb_fetch_rc_items');
add_action('wp_ajax_nopriv_kirb_fetch_rc_items', 'kirb_fetch_rc_items');

function kirb_fetch_rc_items() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';
        $catg = isset($_GET['catg']) ? sanitize_text_field(wp_unslash($_GET['catg'])) : "";
        $user_id = kirb_getCurrentUserId();
        $rc_list = kirb_prepare_rc_list($type, $user_id, $catg);
        if ($rc_list) {
            wp_send_json(
                array(
                    'prod_id_list' => $rc_list,
                    'result' => kirb_fetch_rc_prods($rc_list, $type)
                )
            );
        } else {
            wp_send_json(
                array(
                    'prod_id_list' => [],
                    'result' => array(
                        'html' => '',
                        'stats' => array('count' => 0)
                    )
                )
            );
        }
    }
}

//kirb_reset_byor

add_action('wp_ajax_kirb_reset_byor', 'kirb_reset_byor');
add_action('wp_ajax_nopriv_kirb_reset_byor', 'kirb_reset_byor');

function kirb_reset_byor() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $current_user = kirb_getCurrentUserId();
        global $wpdb;
        $wpdb->delete($wpdb->prefix . 'kirb_byor', array('user_id' => $current_user), array('%s'));
        wp_send_json(array('status' => 'success'));
    }
}


//kirb_delete_prod
add_action('wp_ajax_kirb_del_prod', 'kirb_del_prod');
add_action('wp_ajax_nopriv_kirb_del_prod', 'kirb_del_prod');

function kirb_del_prod() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        global $wpdb;

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

        // Check if diamond or ring is being deleted
        $isDiamond = (isset($_GET['type']) && sanitize_text_field(wp_unslash($_GET['type'])) == 'diamond');
        $hasRingPostId = $byor_data['ring_post_id'] != '0';
        $hasDiamondUid = $byor_data['diamond_uid'] != '0';
        
        // Define column changes based on conditions
        $column = $isDiamond ? ($hasRingPostId ? array('diamond_uid' => 0, 'diamond_type' => 0, 'ord' => 1) : null) : ($hasDiamondUid ? array('ring_post_id' => 0, 'ring_variation_id' => 0, 'ord' => 0) : null);
        
        // Perform update or delete based on conditions
        if ($column) {
            $wpdb->update($wpdb->prefix . 'kirb_byor', $column, array('id' => $byor_id), array('%d'), array('%d'));
        } else {
            $wpdb->delete($wpdb->prefix . 'kirb_byor', array('id' => $byor_id), array('%d'));
        }

        $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);

        $req_type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';
        if($req_type == 'diamond') {
            // redirect page according to diamond category
            $detaildata = kirb_getDiamondByUID($byor_data['diamond_uid'], true);
            $current_category = kirb_getDiamondCategory($detaildata['diamond']['category_id'], null, false);
            $redirect_url = kirb_getPageUrlById($kirb_page_ids[str_replace("kirb-","",$current_category)]);
        } else {
            $redirect_url = get_term_link(get_term_by('slug',kirbGetMeta('_setting_ring_setting_catg'), 'product_cat')); // ring page
        }

        wp_send_json(array('status' => 'success', 'redirect_url' => $redirect_url));
    }
}

// kirb_byor_restart

add_action('wp_ajax_kirb_byor_restart', 'kirb_byor_restart');
add_action('wp_ajax_nopriv_kirb_byor_restart', 'kirb_byor_restart');

function kirb_byor_restart() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        global $wpdb;
        $current_user = kirb_getCurrentUserId();
        $byor_data = kirb_getByorDataForCurrentUser();
        $diamondData = kirb_getDiamondByUID($byor_data['diamond_uid']);
        $diamond_catg_name = kirb_getDiamondCategory($diamondData['diamond']['category_id'], null, false);
        $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);
        $redirect_url = kirb_getPageUrlById($kirb_page_ids[str_replace("kirb-","",KIRB_ALL_CATEGORIES_MAP[$diamond_catg_name])]);
        $wpdb->delete($wpdb->prefix . 'kirb_byor', array('user_id' => $current_user), array('%s'));
        wp_send_json(array('status' => 'success', 'redirect_url' => $redirect_url));
    }
}


//kirb_delete_prod
add_action('wp_ajax_kirb_send_mail', 'kirb_send_mail');
add_action('wp_ajax_nopriv_kirb_send_mail', 'kirb_send_mail');

function kirb_send_mail() {
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'kirb_ajax_nonce')) {
        $data = isset($_GET['data']) ? wp_unslash($_GET['data']) : array();
        $rec_email = isset($data['rec_email']) ? sanitize_email($data['rec_email']) : '';
        $email = isset($data['email']) ? sanitize_email($data['email']) : '';
        $name = isset($data['name']) ? sanitize_text_field($data['name']) : '';
        $message = isset($data['message']) ? sanitize_textarea_field($data['message']) : '';
        $type = isset($data['type']) ? sanitize_text_field($data['type']) : '';
        $phone = isset($data['phone']) ? sanitize_text_field($data['phone']) : '';
        $admin_email = get_option('admin_email');
        $prod_image = isset($data['prod_image']) ? sanitize_url($data['prod_image']) : '';

        $context_type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';
        if($context_type === 'detail') {
            $prod_url = isset($data['prod_url']) ? sanitize_url($data['prod_url']) : '';
            $prod_name = isset($data['prod_name']) ? sanitize_text_field($data['prod_name']) : '';
        }else{
            $prod_url_diamond = isset($data['prod_url_diamond']) ? sanitize_url($data['prod_url_diamond']) : '';
            $prod_url_ring = isset($data['prod_url_ring']) ? sanitize_url($data['prod_url_ring']) : '';
            $prod_name_diamond = isset($data['prod_name_diamond']) ? sanitize_text_field($data['prod_name_diamond']) : '';
            $prod_name_ring = isset($data['prod_name_ring']) ? sanitize_text_field($data['prod_name_ring']) : '';
            $page_url = isset($data['page_url']) ? sanitize_url($data['page_url']) : '';
        }

        $msg_body = esc_html('You\'ve got a new message on').gmdate('F j, Y g:i a T')." from ".'<a href="'.site_url().'">'.site_url().'</a><br><br>';

        if(isset($_GET['type']) && $_GET['type'] == 'detail') {
            $msg_body .= esc_html('Product URL').": ".'<a href="'.$prod_url.'">'.$prod_url."</a><br><br>";
        }else{
            $msg_body .= esc_html('Diamond URL').": ".'<a href="'.$prod_url_diamond.'">'.$prod_url_diamond."</a><br><br>";
            $msg_body .= esc_html('Ring URL').": ".'<a href="'.$prod_url_ring.'">'.$prod_url_ring."</a><br><br>";
        }

        $mail_sent = null;

        if($type == 'dropHint') {
            if($context_type === 'detail') {
                $drop_hint_sender_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/drop-hint-sender.html');
                $drop_hint_recipient_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/drop-hint-recipient.html');

                $data_arr = array(
                    '{{name}}' => $name,
                    '{{email}}' => $email,
                    '{{phone}}' => $phone,
                    '{{message}}' => $message,
                    '{{product_url}}' => $prod_url,
                    '{{product_title}}' => $prod_name,
                    '{{product_image}}' => $prod_image,
                    '{{recipient_email}}' => $rec_email
                );
            }else{
                $drop_hint_sender_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/drop-hint-sender-byor.html');
                $drop_hint_recipient_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/drop-hint-recipient-byor.html');

                $data_arr = array(
                    '{{name}}' => $name,
                    '{{email}}' => $email,
                    '{{phone}}' => $phone,
                    '{{message}}' => $message,
                    '{{product_image}}' => $prod_image,
                    '{{recipient_email}}' => $rec_email,
                    '{{{product_title_ring}}' => $prod_name_ring,
                    '{{product_title_diamond}}' => $prod_name_diamond,
                    '{{ring_url}}' => $prod_url_ring,
                    '{{diamond_url}}' => $prod_url_diamond,
                    '{{page_url}}' => $page_url
                );
            }

            $message_body_sender = str_replace(array_keys($data_arr), array_values($data_arr), $drop_hint_sender_template);
            $message_body_recipient = str_replace(array_keys($data_arr), array_values($data_arr), $drop_hint_recipient_template);

            $subject = esc_html('Drop Hint Received From '.site_url());

            $headers = "From: $email\r\n";
            $headers .= "CC: $admin_email\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

            $mail_sent_sender = mail($rec_email, $subject, $message_body_recipient, $headers);
            $mail_sent_receipient = mail($email, $subject, $message_body_sender, $headers);

            $mail_sent = $mail_sent_sender && $mail_sent_receipient;
        } else {
            if($context_type === 'detail') {
                $request_assistance_sender_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/request-assistance-sender.html');
                $request_assistance_recipient_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/request-assistance-recipient.html');

                $data_arr = array(
                    '{{date}}' => gmdate('j F Y g:i a'),
                    '{{name}}' => $name,
                    '{{email}}' => $email,
                    '{{phone}}' => $phone,
                    '{{message}}' => $message,
                    '{{product_url}}' => $prod_url,
                    '{{product_title}}' => $prod_name,
                    '{{product_image}}' => $prod_image
                );
            }else{
                $request_assistance_sender_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/request-assistance-sender-byor.html');
                $request_assistance_recipient_template = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/admin/email-templates/request-assistance-recipient-byor.html');

                $data_arr = array(
                    '{{date}}' => gmdate('j F Y g:i a'),
                    '{{name}}' => $name,
                    '{{email}}' => $email,
                    '{{phone}}' => $phone,
                    '{{message}}' => $message,
                    '{{product_image}}' => $prod_image,
                    '{{product_title_ring}}' => $prod_name_ring,
                    '{{product_title_diamond}}' => $prod_name_diamond,
                    '{{ring_url}}' => $prod_url_ring,
                    '{{diamond_url}}' => $prod_url_diamond,
                );
            }
            
            $subject = esc_html('Consult Expert');

            $message_body_sender = str_replace(array_keys($data_arr), array_values($data_arr), $request_assistance_sender_template);
            $message_body_recipient = str_replace(array_keys($data_arr), array_values($data_arr), $request_assistance_recipient_template);

            $headers = "From: $email\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            $mail_sent_sender = mail($admin_email, $subject, $message_body_recipient, $headers);
            $mail_sent_receipient = mail($email, $subject, $message_body_sender, $headers);

            $mail_sent = $mail_sent_sender && $mail_sent_receipient;
        }

        if($mail_sent) {
            $toast_msg = esc_html('Mail sent successfully!');
            wp_send_json(array('status' => 'success', 'message' => $toast_msg));
        }else{
            $toast_msg = esc_html('Failed to send mail!');
            wp_send_json(array('status' => 'error', 'message' => $toast_msg));
        }
    }
}

// For auto clearing cache in background if required
add_action('wp_ajax_kirb_ajax_auto_clear_cache', 'kirb_auto_clear_cache_handle');
add_action('wp_ajax_nopriv_kirb_ajax_auto_clear_cache', 'kirb_auto_clear_cache_handle');
function kirb_auto_clear_cache_handle() {
    if (isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'kirb_ajax_nonce')) {
        kirb_auto_clear_cache();
        wp_send_json(array('status' => 'success'));
    }
}

add_action('wp_ajax_kirb_update_ring_size', 'kirb_update_cart_ring_size');
add_action('wp_ajax_nopriv_kirb_update_ring_size', 'kirb_update_cart_ring_size');
function kirb_update_cart_ring_size() {
    check_ajax_referer('kirb_update_ring_size_nonce', 'nonce');
    $cart_item_key = isset($_POST['cart_item_key']) ? sanitize_text_field(wp_unslash($_POST['cart_item_key'])) : '';
    $new_size = isset($_POST['ring_size']) ? sanitize_text_field(wp_unslash($_POST['ring_size'])) : '';
    $cart = WC()->cart->get_cart();
    if (isset($cart[$cart_item_key])) {
        WC()->cart->cart_contents[$cart_item_key]['kirb_custom_data']['ring_size'] = $new_size;
        WC()->cart->cart_contents[$cart_item_key]['kirb_ring_size'] = $new_size;
        WC()->cart->set_session();
        wc_add_notice(('Ring size has been updated successfully.'), 'success');
        wp_send_json_success();
    } else {
        wp_send_json_error('Cart item not found.');
    }
}

function kirb_create_engagement_rings_category($cat_name) {
    $category_name = 'Engagement Rings';
    if($cat_name)
        $category_name = $cat_name;

    $category_slug = sanitize_title_with_dashes($category_name);


    // Check if category exists
    $existing_term = get_term_by('slug', $category_slug, 'product_cat');

    if ($existing_term) {
        $category_id = $existing_term->term_id;
    } else {
        // Create new category
        $new_term = wp_insert_term($category_name, 'product_cat', [
            'slug' => $category_slug
        ]);

        if (is_wp_error($new_term)) {
            wp_send_json_error(['message' => 'Category creation failed']);
        }

        $category_id = $new_term['term_id'];
        $category_slug = get_term($category_id, 'product_cat')->slug;
    }

    kirbAddMeta('_setting_ring_setting_catg', $category_slug);   

    wp_send_json_success(['id' => $category_id, 'slug' => $category_slug, 'name' => $category_name]);
}

// Register AJAX actions
add_action('wp_ajax_kirb_create_engagement_rings_category', 'kirb_create_engagement_rings_category');
add_action('wp_ajax_nopriv_kirb_create_engagement_rings_category', 'kirb_create_engagement_rings_category');


add_action('wp_ajax_kirb_check_atrribute', 'kirb_check_atrribute');
add_action('wp_ajax_nopriv_kirb_check_atrribute', 'kirb_check_atrribute');

function kirb_check_atrribute() {
    $cat_names = ['Engagement Rings', 'Wedding Men Rings', 'Wedding Rings', 'Wedding Women Rings'];

    foreach ($cat_names as $cat_name) {
        $slug = sanitize_title_with_dashes($cat_name);

        $existing_term = get_term_by('slug', $slug, 'product_cat');

        if (!$existing_term || is_wp_error($existing_term)) {
            kirb_create_engagement_rings_category($cat_name); // Pass slug to your creation function
        }
    }

    // Ensure attributes are created after category
    kirb_create_required_attributes();

    wp_send_json_success(['message' => 'Checked/Created engagement ring category and attributes.']);
}

/* phpcs:enable */
