I can’t add my custom product to my woocommerce cart

I am working on a custom plug-in that creates a product type – “roller blind dimensions” and custom variants of this product. Then, in the frontend, the code calculates the price based on the dimensions entered by the customer and those available in the backend. Unfortunately, I can’t manage to add the product to the cart. The product is added but nothing appears in the cart. I can’t find an error, what is wrong in the code, that this product, its variant and dimensions entered by the customer are not added correctly to the woocommerce cart?

// Możesz zdefiniować klasę produktu dla niestandardowego typu produktu
function register_custom_product_type() {
    class WC_Product_Custom_Roll_Dimensions extends WC_Product {
        // Explicitly declare the product_type property
        public $product_type;

        public function __construct( $product ) {
            $this->product_type = 'custom_roll_dimensions';
            parent::__construct( $product );
        }

        // Additional methods specific to this product type
    }

    // Add the custom product type to WooCommerce
    add_filter('product_type_selector', function( $types ){
        $types['custom_roll_dimensions'] = 'Wymiary Rolet';
        return $types;
    });
}

add_action('init', 'register_custom_product_type');

class CustomVariantsManager {


    public function __construct() {
       

        
        add_action('admin_enqueue_scripts', array($this, 'enqueueStyles'));
         add_action('admin_enqueue_scripts', array($this, 'enqueue_and_localize_scripts'));
         add_action('add_meta_boxes', array($this, 'addCustomVariantsMetabox'));

        add_action('save_post', array($this, 'saveCustomVariants'), 10, 2);
        add_action('wp_ajax_custom_variants_pagination', array($this, 'customVariantsPagination'));
        add_action('wp_ajax_nopriv_custom_variants_pagination', array($this, 'customVariantsPagination'));
        add_action('wp_ajax_remove_custom_variant', array($this, 'removeCustomVariantCallback'));
        add_action('wp_ajax_add_custom_variant', array($this, 'addCustomVariantCallback'));
        // Include the kalkulator.php file
        include_once(plugin_dir_path(__FILE__) . 'Kalkulator.php');

    }

    // Enqueue styles for the admin area
    public function enqueueStyles() {
        wp_enqueue_style('moj-wtyczka-styl', plugins_url('css/moj-wtyczka-styl.css', __FILE__));
    }
        
    
    public function enqueue_and_localize_scripts(){
        // Enqueue your JavaScript file
        wp_enqueue_script('custom-variants-scripts', plugin_dir_url(__FILE__) . 'JS/custom-variants-scripts.js', array('jquery'), '1.0', true);

         // Localize the script with necessary data
         wp_localize_script('custom-variants-scripts', 'ajax_object', array(
          'post_id' => get_the_ID(),
            'ajax_url' => admin_url('admin-ajax.php'), // Make sure this points to admin-ajax.php
        ));
         wp_localize_script('custom-variants-scripts', 'custom_script_vars', array(
            'post_id' => get_the_ID(), // Notice the comma here
         ));
    }

    


    
 // Add the custom variants metabox
public function addCustomVariantsMetabox() {
        add_meta_box(
            'custom_variants_metabox_id',   // Unique ID
            'Warianty Produktu',            // Box title
            array($this, 'customVariantsMetaboxHtml'), // Content callback, must be of type callable
             ['product', 'custom_roll_dimensions'], // Dodano wsparcie dla nowego typu produktu
    'normal'
        );
    }
    public function customVariantsMetaboxHtml($post) {
        wp_nonce_field(plugin_basename(__FILE__), 'custom_variants_nonce');
// Retrieve existing variants if any
    $variants = get_post_meta($post->ID, 'custom_variants', true);
    if (!is_array($variants)) {
        $variants = []; // Initialize as an empty array if not an array
    }
    // Retrieve shipping classes
    $shipping_classes = get_terms('product_shipping_class', array('hide_empty' => false));

    echo '<div id="custom_variants_containers">';
    echo '<button id="add_variant" type="button">Dodaj Nowy Wariant</button>';
    echo '<button id="remove_all_variants" type="button">Usuń Wszystkie Warianty</button>';

  $totalVariants = count($variants);
    echo '<div id="total_variants">Wszystkie: ' . $totalVariants . '</div>';
    echo '<div id="custom_variants_container">';
    if ($variants) {
  foreach ($variants as $index => $variant) {
            echo '<div class="variant">';
            $dimensions = esc_attr($variant['width']) . 'x' . esc_attr($variant['height']);
        echo '<style>';
            echo '[id^="variant_dimensions_"] {';
            echo '    margin-left: 10px;';
            echo '}';
            echo '</style>';
            echo '<div id="variant_dimensionsss">';
                echo '<div id="variant_dimensionss" style="display: flex; align-items: center;">';
            echo '<span>ID wariantu: ' . esc_html($variant['id']) . '</span>';  // Dodanie wyświetlania ID wariantu
            echo '<div id="variant_dimensions_' . $index . '" style="display: flex; align-items: center;">';
                    echo '<label="variant_dimensions_' . $index . '">Wymiary:</label>';
                    echo '<span id="variant_dimensions_' . $index . '">' . $dimensions . '</span>';
    echo '</div>';
                echo '</div>';
            echo '<div>';
            echo '<button class="remove_variant" type="button" data-index="' . $index . '">Usuń Wariant</button>';
            echo '<button class="rozwin_variant" type="button" data-index="' . $index . '">Rozwiń</button>';
            echo '</div>';
            echo '</div>';
            echo '<div id="custom_variants_containerx">';
            echo '<div id="custom_variants_container1" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">';
            echo '<div>';
            echo '<label for="variant_width_' . $index . '">Szerokość</label>';
            echo '<input type="text" id="variant_width_' . $index . '" name="variants[' . $index . '][width]" value="' . esc_attr($variant['width']) . '" />';
            echo '</div>';
            echo '<div>';
            echo '<label for="variant_height_' . $index . '">Wysokość</label>';
            echo '<input type="text" id="variant_height_' . $index . '" name="variants[' . $index . '][height]" value="' . esc_attr($variant['height']) . '" />';
            echo '</div>';
            echo '<div>';
            echo '<label for="variant_sku_' . $index . '">SKU</label>';
            echo '<input type="text" id="variant_sku_' . $index . '" name="variants[' . $index . '][sku]" value="' . esc_attr($variant['sku']) . '" />';
            echo '</div>';
            echo '</div>';
            echo '<div id="custom_variants_container2" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">';
            echo '<div>';
            echo '<label for="variant_regular_price_' . $index . '">Cena Regularna</label>';
            echo '<input type="text" id="variant_regular_price_' . $index . '" name="variants[' . $index . '][regular_price]" value="' . esc_attr($variant['regular_price']) . '" size="50" />';
            echo '</div>';
            echo '<div>';
            echo '<label for="variant_sale_price_' . $index . '">Cena Promocyjna</label>';
            echo '<input type="text" id="variant_sale_price_' . $index . '" name="variants[' . $index . '][sale_price]" value="' . esc_attr($variant['sale_price']) . '" size="50" />';
            echo '</div>';
            echo '</div>';
            echo '<div id="custom_variants_container3" style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 0px;">';
            echo '<label for="variant_weight_' . $index . '">Waga</label>';
            echo '<input type="text" id="variant_weight_' . $index . '" name="variants[' . $index . '][weight]" value="' . esc_attr($variant['weight']) . '" size="25" />';
            echo '</div>';
echo '<div>';
echo '<label for="variant_stock_status_' . $index . '">Stan magazynowy:</label>';
echo '<select id="variant_stock_status_' . $index . '" name="variants[' . $index . '][stock_status]">';
echo '<option value="instock"' . (isset($variant['stock_status']) && $variant['stock_status'] === 'instock' ? ' selected' : '') . '>Na stanie</option>';
echo '<option value="outofstock"' . (isset($variant['stock_status']) && $variant['stock_status'] === 'outofstock' ? ' selected' : '') . '>Brak na stanie</option>';
echo '</select>';
echo '</div>';


            echo '<div id="custom_variants_container4" style="display: grid; grid-template-columns: repeat(1, 1fr); gap: px;">';
            // Klasa Wysyłkowa
            echo '<label for="variant_shipping_class_' . $index . '">Klasa Wysyłkowa</label>';
            echo '<select name="variants[' . $index . '][shipping_class]" id="variant_shipping_class_' . $index . '" class="postform">';
            echo '<option value="-1"' . (!isset($variant['shipping_class']) || $variant['shipping_class'] == '-1' ? ' selected="selected"' : '') . '>Taka sama jak nadrzędny</option>';

            foreach ($shipping_classes as $class) {
                $selected = (isset($variant['shipping_class']) && $variant['shipping_class'] == $class->slug) ? ' selected="selected"' : '';
                echo '<option value="' . esc_attr($class->slug) . '"' . $selected . '>' . esc_html($class->name) . '</option>';
            }
            echo '</select>';
            echo '</div>';
          echo '</div>';
            echo '</div>';
        }
    }
echo '<div id="pagination-container"></div>';
echo '</div>'; // Closing tag for "custom_variants_container"
// Dodanie przycisku i pola do przesyłania pliku CSV
echo '<div id="import" class="import-container">';
  echo '<label for="csv_variants">Importuj warianty z pliku CSV:</label>';
    echo '<input type="file" id="csv_variants" name="csv_variants" accept=".csv">';
    echo '<button id="import_csv_btn" class="button_import" onclick="importCsvVariants()">Importuj</button>';
echo '</div>';
}   
    
public function saveCustomVariants($post_id, $post) {
    // Check permissions and security
    if (!current_user_can('edit_post', $post_id) || 
        (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || 
        isset($_REQUEST['bulk_edit']) ||
        (isset($_POST['importing_csv']) && $_POST['importing_csv'] === 'yes') ||
        (!isset($_POST['custom_variants_nonce']) || !wp_verify_nonce($_POST['custom_variants_nonce'], plugin_basename(__FILE__)))) {
        return $post_id;
    }

    // Handle CSV Import
    $custom_variants = get_post_meta($post_id, 'custom_variants', true) ?: [];
    if (isset($_FILES['csv_variants']) && $_FILES['csv_variants']['error'] == UPLOAD_ERR_OK) {
        $file = fopen($_FILES['csv_variants']['tmp_name'], 'r');
        if ($file) {
            fgetcsv($file); // Skip header
            while (($data = fgetcsv($file)) !== FALSE) {
                if (count($data) >= 3) {
                    $new_variant = [
                        'id' => uniqid(), // Dodajemy unikalne ID
                        'width' => sanitize_text_field($data[0]),
                        'height' => sanitize_text_field($data[1]),
                        'regular_price' => sanitize_text_field($data[2]),
                        'sale_price' => '',
                        'weight' => '',
                        'shipping_class' => '-1',
                        'stock_status' => $posted_variant['stock_status'] ?? 'instock' // Ustawienie domyślne na 'Na stanie'
                    ];

                    // Check for duplicates
                    $found = false;
                    foreach ($custom_variants as &$variant) {
                        if ($variant['width'] == $new_variant['width'] && $variant['height'] == $new_variant['height']) {
                            $variant = $new_variant; // Update existing variant
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        $custom_variants[] = $new_variant; // Add new variant
                    }
                }
            }
            fclose($file);
        }
    }
// Initialize an empty array for custom variants
$custom_variants = [];

// Save Custom Variants from Post Data
if (isset($_POST['variants']) && !empty($_POST['variants'])) {
    $custom_variants = []; // Resetujemy tablicę wariantów przed zapisaniem nowych danych
    foreach ($_POST['variants'] as $posted_variant) {
          // Reset the duplicate flag for each variant
        $duplicate_found = false;
        $new_variant = [
            'id' => $posted_variant['id'] ?? uniqid(),
            'width' => sanitize_text_field($posted_variant['width']),
            'height' => sanitize_text_field($posted_variant['height']),
            'regular_price' => floatval($posted_variant['regular_price']),
            'sale_price' => isset($posted_variant['sale_price']) ? floatval($posted_variant['sale_price']) : '',
            'weight' => isset($posted_variant['weight']) ? sanitize_text_field($posted_variant['weight']) : '',
            'sku' => isset($posted_variant['sku']) ? sanitize_text_field($posted_variant['sku']) : '',
            'shipping_class' => isset($posted_variant['shipping_class']) ? sanitize_text_field($posted_variant['shipping_class']) : '',
            'stock_status' => $posted_variant['stock_status'] ?? 'instock' // Ustawienie domyślne na 'Na stanie'
        ];

        // Check for duplicates
       foreach ($custom_variants as &$variant) {
                if ($variant['width'] == $new_variant['width'] && $variant['height'] == $new_variant['height']) {
                    $duplicate_found = true;
                    break;
                }
            }

            if (!$duplicate_found) {
                $custom_variants[] = $new_variant; // Add new variant   
            }
            }
} else {
    // If variants are not set or empty, it means all have been removed
    delete_post_meta($post_id, 'custom_variants'); // Alternatively, use update_post_meta($post_id, 'custom_variants', []);
    return; // Exit the function
}
    update_post_meta($post_id, 'custom_variants', $custom_variants);
 // Zaktualizuj metadane produktu na podstawie wariantów
    if (!empty($custom_variants)) {
        $min_price = PHP_INT_MAX;
        $max_price = PHP_INT_MIN;
        $stock_status = 'instock'; // Domyślnie produkt jest dostępny

        foreach ($custom_variants as $variant) {
            $regular_price = isset($variant['regular_price']) ? floatval($variant['regular_price']) : PHP_INT_MAX;
            $sale_price = isset($variant['sale_price']) && floatval($variant['sale_price']) > 0 ? floatval($variant['sale_price']) : PHP_INT_MAX;
            $current_price = min($regular_price, $sale_price);

            $min_price = min($min_price, $current_price);
            $max_price = max($max_price, $current_price);

            if (isset($variant['stock']) && intval($variant['stock']) <= 0) {
                $stock_status = 'outofstock';
            }
        }

        update_post_meta($post_id, '_min_variation_price', $min_price);
        update_post_meta($post_id, '_max_variation_price', $max_price);
        update_post_meta($post_id, '_stock_status', $stock_status);

        // Usuń wartość _price, aby nie wpływać na inne procesy WooCommerce
        delete_post_meta($post_id, '_price');
    } else {
        // Usuń metadane, jeśli nie ma wariantów
        delete_post_meta($post_id, '_min_variation_price');
        delete_post_meta($post_id, '_max_variation_price');
        delete_post_meta($post_id, '_stock_status');
        delete_post_meta($post_id, '_price');
    }
         // Zaktualizuj metadane produktu na podstawie wariantów
    $stock_status = 'instock'; // Domyślnie produkt jest dostępny

    foreach ($custom_variants as $variant) {
        if (isset($variant['stock']) && $variant['stock'] <= 0) {
            $stock_status = 'outofstock';
            break;
        }
    }

    update_post_meta($post_id, '_stock_status', $stock_status);
    }
    
    
public function removeCustomVariantCallback() {
    $post_id = $_POST['post_id'];
    $indexToRemove = $_POST['index'];

    $custom_variants = get_post_meta($post_id, 'custom_variants', true);

    if(isset($custom_variants[$indexToRemove])) {
        unset($custom_variants[$indexToRemove]);
        update_post_meta($post_id, 'custom_variants', array_values($custom_variants)); // Re-index the array
        echo 'success';
    } else {
        echo 'error';
    }

    wp_die();
}

public function addCustomVariantCallback() {
    $post_id = $_POST['post_id'];
    $newVariant = $_POST['new_variant'];

    $custom_variants = get_post_meta($post_id, 'custom_variants', true);

    // Check if a variant with the same price, width, and height already exists
    foreach ($custom_variants as $variant) {
        if (
            $variant['width'] == $newVariant['width'] &&
            $variant['height'] == $newVariant['height']) {
            echo json_encode(['error' => 'Variant with same price, width, and height already exists']);
            wp_die();
        }
    }

    // Add the new variant to the beginning of the array
    array_unshift($custom_variants, $newVariant);

    // Update the post meta with the new array of variants
    update_post_meta($post_id, 'custom_variants', $custom_variants);

    echo 'success';

    wp_die();
}
     // Dodaj funkcję obsługującą paginację AJAX
    public function customVariantsPagination() {
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $itemsPerPage = 1; // Ilość elementów do wyświetlenia na jednej stronie
        $startIndex = ($page - 1) * $itemsPerPage;

    // Wyślij dane jako JSON
        echo json_encode($variants); // $variants to tablica z wariantami na danej stronie
        wp_die();
    }   
}



 
 // Instantiate the class
$customVariantsManager = new CustomVariantsManager();


add_filter('woocommerce_get_price_html', 'display_price_range_on_product_page', 10, 2);

function display_price_range_on_product_page($price, $product) {
    // Sprawdzenie, czy produkt jest typu 'variable' lub 'custom_roll_dimensions'
    if ($product->is_type('variable') || $product->is_type('custom_roll_dimensions')) {
        $min_price = $product->get_meta('_min_variation_price', true);
        $max_price = $product->get_meta('_max_variation_price', true);

        // Zwracanie zakresu cen, jeśli istnieje różnica pomiędzy minimalną a maksymalną ceną
        if (!empty($min_price) && !empty($max_price) && $min_price != $max_price) {
            return wc_price($min_price) . ' – ' . wc_price($max_price);
        } else if (!empty($min_price)) {
            // Zwracanie tylko minimalnej ceny, jeśli maksymalna jest pusta lub równa minimalnej
            return wc_price($min_price);
        }
    }
    // Dla innych typów produktów, zwracanie oryginalnej ceny
    return $price;
}

Below I present the code that calculates the product price and “adds” the supposedly calculated variant to the WooCommerce cart. However, nothing appears in the cart and it is still empty.


function get_dimension_ranges() {
    $product_title = isset($_POST['product_title']) ? sanitize_text_field($_POST['product_title']) : '';

    // Wyszukiwanie posta (produktu) na podstawie tytułu
    $query = new WP_Query([
        'post_type' => 'product',
        'title' => $product_title
    ]);

    if ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();

        $min_width = PHP_FLOAT_MAX;
        $max_width = PHP_FLOAT_MIN;
        $min_height = PHP_FLOAT_MAX;
        $max_height = PHP_FLOAT_MIN;

        $variants = get_post_meta($post_id, 'custom_variants', true);

        foreach ($variants as $variant) {
            $width = floatval($variant['width']);
            $height = floatval($variant['height']);

            if ($width < $min_width) $min_width = $width;
            if ($width > $max_width) $max_width = $width;
            if ($height < $min_height) $min_height = $height;
            if ($height > $max_height) $max_height = $height;
        }

        wp_send_json([
            'min_width' => $min_width,
            'max_width' => $max_width,
            'min_height' => $min_height,
            'max_height' => $max_height
        ]);
    } else {
        wp_send_json(['error' => 'Produkt nie został znaleziony']);
    }

    wp_die();
}

add_action('wp_ajax_get_dimension_ranges', 'get_dimension_ranges');
add_action('wp_ajax_nopriv_get_dimension_ranges', 'get_dimension_ranges');






function enqueueCalculatorScript() {
    ?>
    <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        var productTitleElement = document.querySelector('.product_title.entry-title');
        var productTitle = productTitleElement.innerText;

        // Fetch and display dimension ranges
        jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {
            'action': 'get_dimension_ranges',
            'product_title': productTitle
        }, function(response) {
            if (!response.error) {
                document.getElementById('min_szerokosc').textContent = response.min_width;
                document.getElementById('max_szerokosc').textContent = response.max_width;
                document.getElementById('min_wysokosc').textContent = response.min_height;
                document.getElementById('max_wysokosc').textContent = response.max_height;
            } else {
                console.error("Dimension range error:", response.error);
            }
        });

       
    var calculateButton = document.getElementById('calculate_price');
    if (calculateButton) {
        calculateButton.addEventListener('click', function() {
            var width = document.getElementById('product_width').value;
            var height = document.getElementById('product_height').value;
            var productTitleElement = document.querySelector('.product_title.entry-title');
            var productTitle = productTitleElement ? productTitleElement.innerText : '';

            jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {
                'action': 'get_variants_for_calculation',
                'width': width,
                'height': height,
                'product_title': productTitle
            }, function(response) {
                var priceDisplay = document.getElementById('calculated_price');
                if (response.error) {
                    priceDisplay.innerHTML = 'Błąd: ' + response.error;
                } else {
                    var priceHtml = response.sale_price ?
                        '<s>' + response.regular_price + '</s> ' + response.sale_price :
                        response.regular_price;
                    priceDisplay.innerHTML = 'Cena: ' + priceHtml;

                    var addButton = document.getElementById('add_to_cart_button');
                    if (!addButton) {
                        addButton = document.createElement('button');
                        addButton.id = 'add_to_cart_button';
                        addButton.innerText = 'Dodaj do koszyka';
                        document.getElementById('product_calculator').appendChild(addButton);
                    }
                    addButton.setAttribute('data-variant-id', response.variant_id);
                    addButton.setAttribute('data-product-id', response.product_id);
                    addButton.setAttribute('data-width', width);
                    addButton.setAttribute('data-height', height);
                    addButton.setAttribute('data-price', priceHtml);
                }
            }, 'json');
        });
    }
});
jQuery(document).ready(function($) {
    $(document).on('click', '#add_to_cart_button', function(e) {
        e.preventDefault();
        var data = {
            'action': 'add_variant_to_cart',
            'product_id': $(this).data('product-id'),
            'variant_id': $(this).data('variant-id')
        };

        $.post(ajax_object.ajax_url, data, function(response) {
            if (response.success) {
                alert('Produkt dodany do koszyka');
                // Opcjonalnie: aktualizacja elementów UI, np. liczba przedmiotów w koszyku
            } else {
                alert('Błąd: ' + response.error);
            }
        });
    });
});


  
    </script>
    <?php
}
add_action('wp_enqueue_scripts', 'enqueueCalculatorScript');



function getVariantsForCalculation() {
    $product_title = isset($_POST['product_title']) ? sanitize_text_field($_POST['product_title']) : '';
    $client_width = isset($_POST['width']) ? floatval(sanitize_text_field($_POST['width'])) : 0;
    $client_height = isset($_POST['height']) ? floatval(sanitize_text_field($_POST['height'])) : 0;

    $query = new WP_Query([
        'post_type' => 'product',
        'title' => $product_title
    ]);

    if ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $variants = get_post_meta($post_id, 'custom_variants', true);

        $nearestVariant = null;
        $smallestDistance = PHP_FLOAT_MAX;

        foreach ($variants as $variant) {
            $distance = sqrt(pow($variant['width'] - $client_width, 2) + pow($variant['height'] - $client_height, 2));
            if ($distance < $smallestDistance) {
                $smallestDistance = $distance;
                $nearestVariant = $variant;
            }
        }

        if ($nearestVariant) {
            echo json_encode([
                'variant_id' => $nearestVariant['id'],
                'regular_price' => $nearestVariant['regular_price'],
                'sale_price' => $nearestVariant['sale_price'],
                'dimensions' => $nearestVariant['width'] . 'x' . $nearestVariant['height'],
                'product_id' => $post_id
            ]);
        } else {
            echo json_encode(['error' => 'No matching variant found']);
        }
    } else {
        echo json_encode(['error' => 'Product not found']);
    }

    wp_die();
}



add_action('wp_ajax_get_variants_for_calculation', 'getVariantsForCalculation');
add_action('wp_ajax_nopriv_get_variants_for_calculation', 'getVariantsForCalculation');





// Dodanie funkcji do akcji AJAX dla zalogowanych i niezalogowanych użytkowników
function add_variant_to_cart() {
    if (!isset($_POST['product_id'], $_POST['variant_id'])) {
        wp_send_json_error(['error' => 'Brakujące dane produktu']);
        wp_die();
    }

    $product_id = intval($_POST['product_id']);
    $variant_id = sanitize_text_field($_POST['variant_id']);
    
    // Pobierz metadane wariantów
    $variants = get_post_meta($product_id, 'custom_variants', true);
    $selected_variant = array_filter($variants, function($v) use ($variant_id) {
        return $v['id'] === $variant_id;
    });

    if(empty($selected_variant)) {
        wp_send_json_error(['error' => 'Wariant nie istnieje']);
        wp_die();
    }

    $selected_variant = array_values($selected_variant)[0];

    $cart_item_data = array(
        'custom_dimensions' => $selected_variant['width'] . 'x' . $selected_variant['height'],
        'custom_price' => $selected_variant['sale_price'] ? $selected_variant['sale_price'] : $selected_variant['regular_price'],
        'stock_status' => $selected_variant['stock_status']
    );

    $cart_item_key = WC()->cart->add_to_cart($product_id, 1, 0, array(), $cart_item_data);

    if (!$cart_item_key) {
        wp_send_json_error(['error' => 'Nie udało się dodać produktu do koszyka']);
        wp_die();
    }

    wp_send_json_success(['success' => 'Produkt dodany do koszyka']);
    wp_die();
}


add_action('wp_ajax_add_variant_to_cart', 'add_variant_to_cart');
add_action('wp_ajax_nopriv_add_variant_to_cart', 'add_variant_to_cart');


function set_custom_price_for_cart_items($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['custom_price'])) {
            $cart_item['data']->set_price($cart_item['custom_price']);
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'set_custom_price_for_cart_items', 10, 1);