I have created a custom WordPress plugin, which creates some custom product types.

When creating/editing a custom product of Type: "Custom Rug", when saving changes, the border options are not being saved. There is some sort of conflict to do with the logic which clears border selects, when the user changes the Rug material...

At the moment that logic correctly clears the border choice, if the Brand of the Rug Material is different to the current brand of the selected border option. This is correct. When a Rug material is changed to something with a different brand it clears the border selects and repopulates them with border materials from that matching brand.

The problem is that the logic to do that seems to be interfering with out ability to save the border options. We have been around in circles a few times trying different things, and nothing seems ot be working.

Please fix the save state of the border drop downs when the user clicks "update", without affecting the other functionality of the conditional dropdowns.


***custom-rug-functions.php:

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function add_custom_rug_product_type( $types ) {
    $types['custom_rug'] = __( 'Custom Rug', 'custom-rug-product' );
    return $types;
}
add_filter( 'product_type_selector', 'add_custom_rug_product_type' );

function add_rug_material_product_type( $types ) {
    $types['rug_material'] = __( 'Rug Material', 'custom-rug-product' );
    return $types;
}
add_filter( 'product_type_selector', 'add_rug_material_product_type' );

function add_border_material_product_type( $types ) {
    $types['border_material'] = __( 'Border Material', 'custom-rug-product' );
    return $types;
}
add_filter( 'product_type_selector', 'add_border_material_product_type' );

function custom_rug_product_class( $classname, $product_type ) {
    if ( $product_type == 'custom_rug' ) {
        $classname = 'WC_Product_Custom_Rug';
    }
    return $classname;
}
add_filter( 'woocommerce_product_class', 'custom_rug_product_class', 10, 2 );

function rug_material_product_class( $classname, $product_type ) {
    if ( $product_type == 'rug_material' ) {
        $classname = 'WC_Product_Rug_Material';
    }
    return $classname;
}
add_filter( 'woocommerce_product_class', 'rug_material_product_class', 10, 2 );

function border_material_product_class( $classname, $product_type ) {
    if ( $product_type == 'border_material' ) {
        $classname = 'WC_Product_Border_Material';
    }
    return $classname;
}
add_filter( 'woocommerce_product_class', 'border_material_product_class', 10, 2 );

function add_custom_product_data_tabs( $tabs ) {
    $tabs['rug_material'] = array(
        'label'    => __( 'Rug Material Options', 'custom-rug-product' ),
        'target'   => 'rug_material_options',
        'class'    => array( 'show_if_rug_material' ),
        'priority' => 21,
    );
    $tabs['border_material'] = array(
        'label'    => __( 'Border Material Options', 'custom-rug-product' ),
        'target'   => 'border_material_options',
        'class'    => array( 'show_if_border_material' ),
        'priority' => 22,
    );
    $tabs['custom_rug'] = array(
        'label'    => __( 'Custom Rug Options', 'custom-rug-product' ),
        'target'   => 'custom_rug_options',
        'class'    => array( 'show_if_custom_rug' ),
        'priority' => 23,
    );
    return $tabs;
}
add_filter( 'woocommerce_product_data_tabs', 'add_custom_product_data_tabs' );

function add_rug_material_options_product_tab_content() {
    global $post;

    echo '<div id="rug_material_options" class="panel woocommerce_options_panel">';

    $fields = array(
        array(
            'id' => '_rug_material_brand',
            'label' => __('Brand', 'custom-rug-product'),
            'type' => 'select',
            'options' => get_brand_options(),
        ),
        array(
            'id' => '_rug_material_material',
            'label' => __('Material', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_product_range',
            'label' => __('Product Range', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_product_code',
            'label' => __('Product Code', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_product_name',
            'label' => __('Product Name', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_product_colour',
            'label' => __('Product Colour', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_sku',
            'label' => __('SKU', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_barcode',
            'label' => __('Barcode', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_rug_material_customer_price',
            'label' => __('Customer Price £ Excl VAT per m2', 'custom-rug-product'),
            'type' => 'number',
            'custom_attributes' => array(
                'step' => 'any',
                'min' => '0'
            )
        ),
    );

    foreach ($fields as $field) {
        $field['required'] = true;
        if (isset($field['type']) && $field['type'] === 'select') {
            woocommerce_wp_select($field);
        } elseif (isset($field['type']) && $field['type'] === 'number') {
            woocommerce_wp_text_input($field);
        } else {
            woocommerce_wp_text_input($field);
        }
    }

    echo '</div>';
}
add_action( 'woocommerce_product_data_panels', 'add_rug_material_options_product_tab_content' );

function add_border_material_options_product_tab_content() {
    global $post;

    echo '<div id="border_material_options" class="panel woocommerce_options_panel">';

    $fields = array(
        array(
            'id' => '_border_material_brand',
            'label' => __('Brand', 'custom-rug-product'),
            'type' => 'select',
            'options' => get_brand_options(),
        ),
        array(
            'id' => '_border_material_material',
            'label' => __('Material', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_product_range',
            'label' => __('Product Range', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_product_code',
            'label' => __('Product Code', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_product_name',
            'label' => __('Product Name', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_product_colour',
            'label' => __('Product Colour', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_sku',
            'label' => __('SKU', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_barcode',
            'label' => __('Barcode', 'custom-rug-product'),
            'type' => 'text',
        ),
        array(
            'id' => '_border_material_customer_price',
            'label' => __('Customer Price £ Excl VAT per linear m', 'custom-rug-product'),
            'type' => 'number',
            'custom_attributes' => array(
                'step' => 'any',
                'min' => '0'
            )
        ),
    );

    foreach ($fields as $field) {
        $field['required'] = true;
        if (isset($field['type']) && $field['type'] === 'select') {
            woocommerce_wp_select($field);
        } elseif (isset($field['type']) && $field['type'] === 'number') {
            woocommerce_wp_text_input($field);
        } else {
            woocommerce_wp_text_input($field);
        }
    }

    echo '</div>';
}
add_action( 'woocommerce_product_data_panels', 'add_border_material_options_product_tab_content' );

function get_brand_settings_and_border_materials_ajax() {
    check_ajax_referer('custom_rug_ajax_nonce', 'security');

    $rug_material_id = isset($_POST['rug_material_id']) ? intval($_POST['rug_material_id']) : 0;
    
    $brand_id = get_post_meta($rug_material_id, '_rug_material_brand', true);
    $brand_settings = get_option('custom_rug_brand_settings_' . $brand_id, array());

    // Get the brand name instead of the ID
    $brands = get_option('custom_rug_brands', array());
    $brand_name = isset($brands[$brand_id]) ? $brands[$brand_id] : '';

    $rug_material_info = array(
        'brand' => $brand_name,
        'brand_id' => $brand_id,
        'material' => get_post_meta($rug_material_id, '_rug_material_material', true),
        'customer_price' => get_post_meta($rug_material_id, '_rug_material_customer_price', true),
    );

    $args = array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'slug',
                'terms'    => 'border_material',
            ),
        ),
        'meta_query' => array(
            array(
                'key' => '_border_material_brand',
                'value' => $brand_id,
            ),
        ),
        'posts_per_page' => -1,
    );

    $border_materials = get_posts($args);

    $border_options = array();
    $border_info = array();
    foreach ($border_materials as $material) {
        $border_options[$material->ID] = $material->post_title;
        $border_info[$material->ID] = array(
            'material' => get_post_meta($material->ID, '_border_material_material', true),
            'customer_price' => get_post_meta($material->ID, '_border_material_customer_price', true),
            'brand' => get_post_meta($material->ID, '_border_material_brand', true),
        );
    }

    $outer_border_widths = array_map('trim', explode(';', $brand_settings['available_outer_border_widths'] ?? ''));
    $inner_border_widths = array_map('trim', explode(';', $brand_settings['available_inner_border_widths'] ?? ''));

    wp_send_json(array(
        'brand_settings' => $brand_settings,
        'border_materials' => $border_options,
        'border_info' => $border_info,
        'outer_border_widths' => $outer_border_widths,
        'inner_border_widths' => $inner_border_widths,
        'rug_material_info' => $rug_material_info,
    ));
}

add_action('wp_ajax_get_brand_settings_and_border_materials', 'get_brand_settings_and_border_materials_ajax');


function add_custom_rug_options_product_tab_content() {
    global $post;

    echo '<div id="custom_rug_options" class="panel woocommerce_options_panel">';

    $fields = array(
        '_custom_rug_length' => array('label' => 'Rug Length (cm)', 'type' => 'number'),
        '_custom_rug_width' => array('label' => 'Rug Width (cm)', 'type' => 'number'),
        '_custom_rug_material' => array('label' => 'Rug Material', 'type' => 'select'),
        '_custom_rug_outer_border_material' => array('label' => 'Outer Border Material', 'type' => 'select'),
        '_custom_rug_outer_border_width' => array('label' => 'Outer Border Width (cm)', 'type' => 'select'),
        '_custom_rug_inner_border_material' => array('label' => 'Inner Border Material', 'type' => 'select'),
        '_custom_rug_inner_border_width' => array('label' => 'Inner Border Width (cm)', 'type' => 'select'),
        '_custom_rug_stain_protection' => array('label' => 'Stain Protection', 'type' => 'checkbox')
    );

    foreach ($fields as $field_id => $field_data) {
        $value = get_post_meta($post->ID, $field_id, true);
        error_log("Loading $field_id with value: $value"); // Debug log

        $field = array(
            'id' => $field_id,
            'label' => __($field_data['label'], 'custom-rug-product'),
            'value' => $value,
            'custom_attributes' => array('data-saved-value' => $value)
        );

        if ($field_data['type'] === 'number') {
            $field['type'] = 'number';
            $field['custom_attributes']['step'] = 'any';
            $field['custom_attributes']['min'] = '0';
            woocommerce_wp_text_input($field);
        } elseif ($field_data['type'] === 'select') {
            $field['options'] = array('' => __('Select an option', 'custom-rug-product'));
            woocommerce_wp_select($field);
        } elseif ($field_data['type'] === 'checkbox') {
            woocommerce_wp_checkbox($field);
        }
    }

    echo '</div>';
}

add_action( 'woocommerce_product_data_panels', 'add_custom_rug_options_product_tab_content' );

function save_product_options($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    $product_type = isset($_POST['product-type']) ? sanitize_title($_POST['product-type']) : 'simple';

    if ($product_type === 'rug_material' || $product_type === 'border_material') {
        $fields = array(
            '_' . $product_type . '_brand',
            '_' . $product_type . '_material',
            '_' . $product_type . '_product_range',
            '_' . $product_type . '_product_code',
            '_' . $product_type . '_product_name',
            '_' . $product_type . '_product_colour',
            '_' . $product_type . '_sku',
            '_' . $product_type . '_barcode',
            '_' . $product_type . '_customer_price'
        );

        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_text_field($_POST[$field]);
                update_post_meta($post_id, $field, $value);
                
                if ($field === '_' . $product_type . '_product_name') {
                    wp_update_post(array(
                        'ID' => $post_id,
                        'post_title' => $value,
                    ));
                }
                
                if ($field === '_' . $product_type . '_sku') {
                    update_post_meta($post_id, '_sku', $value);
                }
            }
        }
    } elseif ($product_type === 'custom_rug') {
        $custom_rug_fields = array(
            '_custom_rug_length',
            '_custom_rug_width',
            '_custom_rug_material',
            '_custom_rug_outer_border_material',
            '_custom_rug_outer_border_width',
            '_custom_rug_inner_border_material',
            '_custom_rug_inner_border_width',
            '_custom_rug_stain_protection'
        );

        foreach ($custom_rug_fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_text_field($_POST[$field]);
                update_post_meta($post_id, $field, $value);
            }
        }

        // Special handling for checkbox fields
        $stain_protection = isset($_POST['_custom_rug_stain_protection']) ? 'yes' : 'no';
        update_post_meta($post_id, '_custom_rug_stain_protection', $stain_protection);
    }
}
add_action('woocommerce_process_product_meta', 'save_product_options', 10, 1);


function get_brand_options() {
    $brands = get_option('custom_rug_brands', array());
    $options = array('' => __('Select a brand', 'custom-rug-product'));
    foreach ($brands as $brand_id => $brand_name) {
        $options[$brand_id] = $brand_name;
    }
    return $options;
}

function enqueue_custom_rug_admin_script() {
    global $post_type;
    if ('product' !== $post_type) {
        return;
    }

    $script_path = plugins_url('js/custom-rug-script.js', dirname(__FILE__));
    wp_enqueue_script('custom-rug-admin-script', $script_path, array('jquery'), '1.0.0', true);
    wp_localize_script('custom-rug-admin-script', 'custom_rug_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'security' => wp_create_nonce('custom_rug_ajax_nonce')
    ));
}
add_action('admin_enqueue_scripts', 'enqueue_custom_rug_admin_script');

function add_custom_rug_identifier() {
    echo '<input type="hidden" name="custom_rug_product" value="1">';
}
add_action('woocommerce_product_options_general_product_data', 'add_custom_rug_identifier');

function add_product_type_column_header( $columns ) {
    $new_columns = array();

    foreach ( $columns as $key => $value ) {
        $new_columns[ $key ] = $value;

        if ( $key === 'sku' ) {
            $new_columns['product_type'] = __( 'Product Type', 'custom-rug-product' );
        }
    }

    return $new_columns;
}
add_filter( 'manage_edit-product_columns', 'add_product_type_column_header', 10 );

function add_product_type_column_content( $column, $post_id ) {
    if ( $column === 'product_type' ) {
        $product = wc_get_product( $post_id );
        if ( $product ) {
            echo esc_html( $product->get_type() );
        }
    }
}
add_action( 'manage_product_posts_custom_column', 'add_product_type_column_content', 10, 2 );

function hide_standard_fields_for_custom_types() {
    global $post_type;
    if ($post_type !== 'product') return;

    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        function hideFields() {
            var productType = $('#product-type').val();
            if (productType === 'rug_material' || productType === 'border_material') {
                $('#postdivrich, #postexcerpt, #commentsdiv, #commentstatusdiv').hide();
            } else {
                $('#postdivrich, #postexcerpt, #commentsdiv, #commentstatusdiv').show();
            }
        }

        hideFields();
        $('#product-type').on('change', hideFields);
        setInterval(hideFields, 1000);
    });
    </script>
    <?php
}
add_action('admin_footer', 'hide_standard_fields_for_custom_types');

function get_product_type() {
    global $post;
    if (isset($_GET['post_type'])) {
        return $_GET['post_type'];
    } elseif (isset($_POST['product-type'])) {
        return $_POST['product-type'];
    } elseif (isset($post) && is_object($post)) {
        return get_post_meta($post->ID, '_product_type', true);
    }
    return 'simple';
}

function get_rug_materials_ajax() {
    check_ajax_referer('custom_rug_ajax_nonce', 'security');

    $args = array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'slug',
                'terms'    => 'rug_material',
            ),
        ),
        'posts_per_page' => -1,
    );

    $rug_materials = get_posts($args);

    $options = array('' => __('Select a rug material', 'custom-rug-product'));
    foreach ($rug_materials as $material) {
        $options[$material->ID] = $material->post_title;
    }

    wp_send_json($options);
}
add_action('wp_ajax_get_rug_materials', 'get_rug_materials_ajax');

function add_custom_rug_admin_styles() {
    global $post_type;
    if ('product' === $post_type) {
        ?>
        <style type="text/css">
            .custom-rug-info table {
                font-size: 13px;
            }
            .custom-rug-info th {
                background-color: #f1f1f1;
            }
            .custom-rug-info td, .custom-rug-info th {
                padding: 8px !important;
            }
        </style>
        <?php
    }
}
add_action('admin_head', 'add_custom_rug_admin_styles');


function get_border_materials_ajax() {
    check_ajax_referer('custom_rug_ajax_nonce', 'security');

    $args = array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'slug',
                'terms'    => 'border_material',
            ),
        ),
        'posts_per_page' => -1,
    );

    $border_materials = get_posts($args);

    $options = array('' => __('Select a border material', 'custom-rug-product'));
    foreach ($border_materials as $material) {
        $options[$material->ID] = $material->post_title;
    }

    wp_send_json($options);
}
add_action('wp_ajax_get_border_materials', 'get_border_materials_ajax');



***custom-rug-script.js:

jQuery(document).ready(function($) {
    console.log('Custom Rug script loaded');

    function show_hide_panels() {
        var product_type = $('#product-type').val();
        console.log('Product type changed to:', product_type);

        $('.woocommerce_options_panel').hide();
        $('#' + product_type + '_options').show();

        if (product_type === 'rug_material') {
            $('#_rug_material_brand').closest('.form-field').show();
            $('#_border_material_brand').closest('.form-field').hide();
            $('#_rug_material_customer_price').closest('.form-field').show();
            $('#_border_material_customer_price').closest('.form-field').hide();
        } else if (product_type === 'border_material') {
            $('#_rug_material_brand').closest('.form-field').hide();
            $('#_border_material_brand').closest('.form-field').show();
            $('#_rug_material_customer_price').closest('.form-field').hide();
            $('#_border_material_customer_price').closest('.form-field').show();
        }
    }

    $('#product-type').change(show_hide_panels);
    show_hide_panels();

    function updateWooCommerceProductName() {
        var product_type = $('#product-type').val();
        if (product_type === 'rug_material' || product_type === 'border_material') {
            var custom_name = $('#_' + product_type + '_product_name').val();
            var $title = $('#title');
            var $titlePrompt = $('#title-prompt-text');
            
            if (custom_name) {
                $title.val(custom_name);
                $titlePrompt.hide();
            } else {
                var default_title = 'Untitled ' + product_type.replace('_', ' ');
                $title.val(default_title);
                $titlePrompt.hide();
            }

            $title.trigger('change');
        }
    }

    $('#_rug_material_product_name, #_border_material_product_name').on('input', updateWooCommerceProductName);

    $('form#post').on('submit', function(e) {
        updateWooCommerceProductName();
    });

    function populateRugMaterials(callback) {
        var currentProductId = $('#post_ID').val();
        var currentProductName = $('#title').val();
        
        $.ajax({
            url: custom_rug_ajax.ajax_url,
            type: 'POST',
            data: {
                'action': 'get_rug_materials',
                'security': custom_rug_ajax.security
            },
            success: function(response) {
                var $select = $('#_custom_rug_material');
                var currentValue = $select.val();
                
                $select.empty();
                $select.append($('<option></option>').val('').text('Select a rug material'));
                
                $.each(response, function(value, text) {
                    if (value !== '' && value !== currentProductId && text !== currentProductName) {
                        $select.append($('<option></option>').val(value).text(text));
                    }
                });

                $select.val(currentValue);

                if (typeof callback === 'function') {
                    callback();
                }
            }
        });
    }

    function updateBorderOptions() {
        var rugMaterialId = $('#_custom_rug_material').val();
        
        if (rugMaterialId) {
            $.ajax({
                url: custom_rug_ajax.ajax_url,
                type: 'POST',
                data: {
                    'action': 'get_brand_settings_and_border_materials',
                    'security': custom_rug_ajax.security,
                    'rug_material_id': rugMaterialId
                },
                success: function(response) {
                    console.log('AJAX Response:', response);

                    var brandSettings = response.brand_settings;
                    var borderMaterials = response.border_materials;
                    var borderInfo = response.border_info;
                    var outerBorderWidths = response.outer_border_widths;
                    var innerBorderWidths = response.inner_border_widths;
                    var rugMaterialInfo = response.rug_material_info;

                    var $outerBorder = $('#_custom_rug_outer_border_material');
                    var $innerBorder = $('#_custom_rug_inner_border_material');
                    var $outerBorderWidth = $('#_custom_rug_outer_border_width');
                    var $innerBorderWidth = $('#_custom_rug_inner_border_width');

                    var currentOuterBorder = $outerBorder.val();
                    var currentInnerBorder = $innerBorder.val();
                    var currentOuterWidth = $outerBorderWidth.val();
                    var currentInnerWidth = $innerBorderWidth.val();

                    $outerBorder.empty().append($('<option></option>').val('').text('Select a border material'));
                    $innerBorder.empty().append($('<option></option>').val('').text('Select a border material'));
                    $.each(borderMaterials, function(value, text) {
                        $outerBorder.append($('<option></option>').val(value).text(text));
                        $innerBorder.append($('<option></option>').val(value).text(text));
                    });

                    $outerBorderWidth.empty().append($('<option></option>').val('').text('Select outer border width'));
                    $innerBorderWidth.empty().append($('<option></option>').val('').text('Select inner border width'));
                    $.each(outerBorderWidths, function(index, width) {
                        $outerBorderWidth.append($('<option></option>').val(width).text(width + ' cm'));
                    });
                    $.each(innerBorderWidths, function(index, width) {
                        $innerBorderWidth.append($('<option></option>').val(width).text(width + ' cm'));
                    });

                    $outerBorder.val(currentOuterBorder);
                    $innerBorder.val(currentInnerBorder);
                    $outerBorderWidth.val(currentOuterWidth);
                    $innerBorderWidth.val(currentInnerWidth);

                    if (brandSettings.can_do_outer_border) {
                        $outerBorder.closest('.form-field').show();
                        $outerBorderWidth.closest('.form-field').show();
                    } else {
                        $outerBorder.closest('.form-field').hide();
                        $outerBorderWidth.closest('.form-field').hide();
                    }

                    if (brandSettings.can_do_inner_border) {
                        $innerBorder.closest('.form-field').show();
                        $innerBorderWidth.closest('.form-field').show();
                    } else {
                        $innerBorder.closest('.form-field').hide();
                        $innerBorderWidth.closest('.form-field').hide();
                    }

                    if (brandSettings.can_do_stain_protection) {
                        $('#_custom_rug_stain_protection').closest('.form-field').show();
                    } else {
                        $('#_custom_rug_stain_protection').closest('.form-field').hide();
                    }

                    updateInfoDisplay(rugMaterialInfo, borderInfo, $outerBorder, $innerBorder);
                }
            });
        } else {
            $('#_custom_rug_outer_border_material, #_custom_rug_inner_border_material, #_custom_rug_outer_border_width, #_custom_rug_inner_border_width, #_custom_rug_stain_protection')
                .closest('.form-field').hide();
            $('.custom-rug-info').remove();
        }
    }

    $('#_custom_rug_material').on('change', updateBorderOptions);

    function initializeCustomRugFields() {
        if ($('#product-type').val() === 'custom_rug') {
            populateRugMaterials(function() {
                $('#_custom_rug_material').val($('#_custom_rug_material').data('saved-value'));
                $('#_custom_rug_outer_border_material').val($('#_custom_rug_outer_border_material').data('saved-value'));
                $('#_custom_rug_inner_border_material').val($('#_custom_rug_inner_border_material').data('saved-value'));
                $('#_custom_rug_outer_border_width').val($('#_custom_rug_outer_border_width').data('saved-value'));
                $('#_custom_rug_inner_border_width').val($('#_custom_rug_inner_border_width').data('saved-value'));
                
                if ($('#_custom_rug_stain_protection').data('saved-value') === 'yes') {
                    $('#_custom_rug_stain_protection').prop('checked', true);
                }

                updateBorderOptions();
            });
        }
    }

    $('#product-type').on('change', function() {
        if ($(this).val() === 'custom_rug') {
            initializeCustomRugFields();
        }
    });

    initializeCustomRugFields();

    function updateInfoDisplay(rugMaterialInfo, borderInfo, $outerBorder, $innerBorder) {
        $('.custom-rug-info').remove();
        var infoHtml = '<div class="custom-rug-info" style="margin-top: 20px; padding: 10px; background-color: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">';
        
        infoHtml += '<table style="width: 100%; border-collapse: collapse;">';
        infoHtml += '<tr><th colspan="2" style="text-align: left; padding: 5px; border-bottom: 1px solid #ddd;">Selected Materials Info</th></tr>';
        
        infoHtml += '<tr><td style="padding: 5px; width: 30%;"><strong>Brand:</strong></td><td style="padding: 5px;">' + rugMaterialInfo.brand + '</td></tr>';
        
        infoHtml += '<tr><td style="padding: 5px; width: 30%;"><strong>Rug Material:</strong></td><td style="padding: 5px;">' + rugMaterialInfo.material + '</td></tr>';
        infoHtml += '<tr><td style="padding: 5px;"><strong>Price:</strong></td><td style="padding: 5px;">£' + rugMaterialInfo.customer_price + ' per m² (excl. VAT)</td></tr>';
        
        function getBorderMaterialInfo($select) {
            var selectedId = $select.val();
            var selectedText = $select.find('option:selected').text();
            if (selectedId && borderInfo[selectedId]) {
                var info = borderInfo[selectedId];
                return '<tr><td style="padding: 5px;"><strong>Material:</strong></td><td style="padding: 5px;">' + info.material + '</td></tr>' +
                       '<tr><td style="padding: 5px;"><strong>Price:</strong></td><td style="padding: 5px;">£' + info.customer_price + ' per linear m (excl. VAT)</td></tr>';
            } else if (selectedId) {
                return '<tr><td style="padding: 5px;"><strong>Selected:</strong></td><td style="padding: 5px;">' + selectedText + '</td></tr>';
            }
            return '';
        }

        var outerBorderSelected = $outerBorder.val();
        if (outerBorderSelected) {
            infoHtml += '<tr><th colspan="2" style="text-align: left; padding: 5px; border-bottom: 1px solid #ddd;">Outer Border</th></tr>';
            infoHtml += getBorderMaterialInfo($outerBorder);
        }

        var innerBorderSelected = $innerBorder.val();
        if (innerBorderSelected) {
            infoHtml += '<tr><th colspan="2" style="text-align: left; padding: 5px; border-bottom: 1px solid #ddd;">Inner Border</th></tr>';
            infoHtml += getBorderMaterialInfo($innerBorder);
        }

        infoHtml += '</table>';
        infoHtml += '</div>';
        $('#custom_rug_options').append(infoHtml);
    }
});

***custom-wc-product-custom-rug.php:

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class WC_Product_Custom_Rug extends WC_Product {
    public function __construct( $product ) {
        $this->product_type = 'custom_rug';
        parent::__construct( $product );
    }

    public function get_type() {
        return 'custom_rug';
    }

    // Add any additional methods specific to your custom rug product
}


***class-wc-product-border-material.php:

<?php
if (!defined('ABSPATH')) {
    exit;
}

class WC_Product_Border_Material extends WC_Product {
    public function __construct($product) {
        $this->product_type = 'border_material';
        parent::__construct($product);
    }

    public function get_type() {
        return 'border_material';
    }
}

***class-wc-product-rug-material.php
<?php
if (!defined('ABSPATH')) {
    exit;
}

class WC_Product_Rug_Material extends WC_Product {
    public function __construct($product) {
        $this->product_type = 'rug_material';
        parent::__construct($product);
    }

    public function get_type() {
        return 'rug_material';
    }
}

***custom-rug-product.php:

<?php
/*
Plugin Name: Custom Rug Product for Natural Rug Company
Plugin URI: https://yourwebsite.com/
Description: Adds a custom rug product type to WooCommerce
Version: 1.0
Author: Ben Ellis-Gowland
Author URI: https://yourwebsite.com/
License: GPL2
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

// Initialize the plugin
add_action( 'plugins_loaded', 'initialize_custom_rug_product', 20 );

function initialize_custom_rug_product() {
    // Check if WooCommerce is active
    if ( ! class_exists( 'WooCommerce' ) ) {
        add_action( 'admin_notices', 'custom_rug_product_woocommerce_deactivated' );
        return;
    }

    // Include the custom product classes
    $class_files = array(
        'class-wc-product-custom-rug.php',
        'class-wc-product-rug-material.php',
        'class-wc-product-border-material.php'
    );

    foreach ($class_files as $file) {
        $class_file = plugin_dir_path( __FILE__ ) . 'includes/' . $file;
        if ( file_exists( $class_file ) ) {
            require_once $class_file;
        } else {
            add_action( 'admin_notices', 'custom_rug_product_missing_files' );
            return;
        }
    }

    // Include functions to register and handle the custom product type
    $functions_file = plugin_dir_path( __FILE__ ) . 'includes/custom-rug-functions.php';
    if ( file_exists( $functions_file ) ) {
        require_once $functions_file;
    } else {
        add_action( 'admin_notices', 'custom_rug_product_missing_files' );
        return;
    }

    // Include admin menu and settings
    if ( is_admin() ) {
        $admin_file = plugin_dir_path( __FILE__ ) . 'admin/admin-menu.php';
        if ( file_exists( $admin_file ) ) {
            require_once $admin_file;
        } else {
            add_action( 'admin_notices', 'custom_rug_product_missing_files' );
            return;
        }
    }
}

function custom_rug_product_woocommerce_deactivated() {
    echo '<div class="error"><p><strong>Custom Rug Product</strong> requires WooCommerce to be installed and active.</p></div>';
}

function custom_rug_product_missing_files() {
    echo '<div class="error"><p><strong>Custom Rug Product</strong> is missing required files. Please reinstall the plugin.</p></div>';
}