<?php
/**
 * OceanWP Child Theme Functions
 *
 * Functions file for child theme of OceanWP, includes parent styles and customizes WooCommerce functionality.
 *
 * Text Domain: oceanwp
 * @link http://codex.wordpress.org/Theme_Development
 * @link http://codex.wordpress.org/Child_Themes
 * @link http://codex.wordpress.org/Plugin_API
 */

/**
 * Enqueue parent and child styles.
 */
function oceanwp_child_enqueue_parent_style() {
    $parent_style = 'oceanwp-style';
    $child_style = 'child-style';

    $theme = wp_get_theme('OceanWP');
    $version = $theme->get('Version');

    wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css', [], $version);
    wp_enqueue_style($child_style, get_stylesheet_directory_uri() . '/style.css', [$parent_style], $version);
}
add_action('wp_enqueue_scripts', 'oceanwp_child_enqueue_parent_style');

/**
 * Prevent direct access to PHP files.
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Make zip/postcode field optional at checkout.  - Morli
 */
function QuadLayers_optional_postcode_checkout($fields) {
    $fields['postcode']['required'] = false;
    return $fields;
}
add_filter('woocommerce_default_address_fields', 'QuadLayers_optional_postcode_checkout');

/**
 * change options text.  - Morli
 */
add_filter('woocommerce_dropdown_variation_attribute_options_args', 'custom_variation_dropdown_args', 10);

function custom_variation_dropdown_args($args) {
    $args['show_option_none'] = __('בחירת גודל >> ', 'oceanwp'); // Use OceanWP's text domain
    return $args;
}

/* Morli  */
// Add this code to your theme's functions.php file to enable custom link to add product and forward to checkout
/*********** function custom_add_to_cart_url() {
    if (is_product()) {
        global $product;
        $product_id = $product->get_id();
        $custom_page_url = 'https://promotop.co.il/c1-generators-sell'; // Replace with your custom page URL
        $add_to_cart_url = $custom_page_url . '/?add-to-cart=' . $product_id . '&quantity=1';
        return $add_to_cart_url;
    }
    return '';
}
add_shortcode('custom_add_to_cart', 'custom_add_to_cart_url');

****************/
 
/* End Morli  */


/*
Custom WC Webhook Manager
Add new webhook topic only for WC order completed.
Developed by Md Jahidul Islam ( oneTarek ) https://onetarek.com
*/ 

//Don't allow direct access
if( ! defined( 'ABSPATH' ) ) exit;

if( ! class_exists( 'Custom_WC_Webhook_Manager' ) ) :
    
    class Custom_WC_Webhook_Manager {
        
        public function __construct() {  
            
            add_filter('woocommerce_webhook_topics', array( $this, 'add_custom_webhook_topics' ), 10, 1 );
            add_action('woocommerce_order_status_completed', array( $this, 'on_woocommerce_order_status_completed' ), 10, 2 );
            add_filter('woocommerce_webhook_payload', array( $this, 'add_custom_webhook_payload' ), 10, 4 );

        }

    
        /*
        Custom topics must start with 'action.woocommerce_' or 'action.wc_'
        described in the function wc_is_webhook_valid_topic
        If the topic name starts with 'action' then there must has a wp hook named with the string used after dot(.)
        So for this Topic we must have a wp hook 'wc_custom_order_completed'.
        Adding custom topic hooks using filter 'woocommerce_webhook_topic_hooks' does not work here.
        */

        public function add_custom_webhook_topics( $topics ){
            $topics['action.wc_custom_order_completed'] = 'Custom Order completed';
            return $topics;
        }

        //Trigger wc_custom_order_completed hook on woocommerce_order_status_completed hook.
        public function on_woocommerce_order_status_completed( $order_id, $order ){
            // We could use 'woocommerce_order_status_completed' hook name directly with the topic name.
            // But we are not using that directly because, if in future WC plugin adds new topic using that hook.
            do_action('wc_custom_order_completed', $order_id, $order );
            
            // Add a logging statement for debugging
            error_log("Custom Order Completed hook triggered for order ID: $order_id");
        }

        /*
         * Set payload for our custom topic.
         */
        public function add_custom_webhook_payload( $payload, $resource, $resource_id, $webhook_id ) {
            if( isset( $payload['action'] ) && $payload['action'] == 'wc_custom_order_completed' && !empty( $payload['arg'] ) ) {
                $webhook = wc_get_webhook( $webhook_id );
                // Build the payload with the same user context as the user who created
                // the webhook -- this avoids permission errors as background processing
                // runs with no user context.
                // See build_payload() in woocommerce/includes/class-wc-webhook.php
                $current_user = get_current_user_id();
                wp_set_current_user( $webhook->get_user_id() );

                $version = str_replace( 'wp_api_', '', $webhook->get_api_version() );
                $resource = 'order';
                $payload = wc()->api->get_endpoint_data( "/wc/{$version}/{$resource}s/{$resource_id}" );

                // Restore the current user.
                wp_set_current_user( $current_user );
                
                // Add a logging statement for debugging
                error_log("Adding custom webhook payload for order ID: $resource_id");
            }
            return $payload;
        }
    
    }//end class
    
endif;

$Custom_WC_Webhook_Manager = new Custom_WC_Webhook_Manager();


/*  ביטול באנר מבצע */
add_filter('woocommerce_sale_flash', '__return_false');


/********************  הגדרת מינימום כמות למוצר ותוספת של סיכום מידות ובדיקת מינמום  *********************/
/******************** הגדרת מינמום כמות למוצר *********************/
function enforce_minimum_quantity_input_custom_field( $quantity_input, $product ) {
    $minimum_quantity = get_post_meta( $product->get_id(), 'product_min_qty', true );
 
    if ( $minimum_quantity ) {
        $quantity_input['min_value'] = $minimum_quantity;
        $quantity_input['value'] = $minimum_quantity; // Set the default value
    }
 
    return $quantity_input;
}
add_filter( 'woocommerce_quantity_input_args', 'enforce_minimum_quantity_input_custom_field', 10, 2 );
 
function set_minimum_quantity_custom_field( $passed, $product_id, $quantity, $variation_id = null ) {
    $minimum_quantity = get_post_meta( $product_id, 'product_min_qty', true );
 
    if ( $minimum_quantity && $quantity < $minimum_quantity ) {
        $error_message = sprintf(
            __( 'מינימום הכמות להזמנה הוא: %s', 'woocommerce' ),
            $minimum_quantity
        );
 
        wc_add_notice( $error_message, 'error' );
        $passed = false;
    }
    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'set_minimum_quantity_custom_field', 10, 4 );

/**************************סוף הגדרת מינמום כמות למוצר ***************************/

/******************** חולצות עיצוב אישי - סיכום כמויות *********************/

/******************** חסימת האפשרות של עדכון כמות בעגלה עבור חולצות עיצוב אישי *********************/

// Store product ID in cart item data for custom shirts
function mark_custom_shirt_cart_items($cart_item_data, $product_id, $variation_id) {
    if (has_term('חולצה- מידות-עיצוב אישי', 'product_tag', $product_id)) {
        $cart_item_data['is_custom_shirt'] = true;
        $cart_item_data['custom_shirt_product_id'] = $product_id;
    }
    return $cart_item_data;
}
add_filter('woocommerce_add_cart_item_data', 'mark_custom_shirt_cart_items', 10, 3);

// Pass custom shirt product IDs to JavaScript
function pass_custom_shirt_ids_to_js() {
    if (is_cart()) {
        $custom_shirt_ids = array();
        
        foreach (WC()->cart->get_cart() as $cart_item) {
            if (isset($cart_item['is_custom_shirt']) && $cart_item['is_custom_shirt']) {
                $custom_shirt_ids[] = $cart_item['custom_shirt_product_id'];
            }
        }
        
        if (!empty($custom_shirt_ids)) {
            ?>
            <script>
            var customShirtProductIds = <?php echo json_encode($custom_shirt_ids); ?>;
            console.log('Custom shirt product IDs in cart:', customShirtProductIds);
            </script>
            <?php
        }
    }
}
add_action('wp_footer', 'pass_custom_shirt_ids_to_js', 5);

// Disable quantity changes for custom shirts in cart
function disable_custom_shirt_quantity_in_cart() {
    if (is_cart()) {
        ?>
        <script>
        jQuery(document).ready(function($) {
            console.log('Cart quantity disable script loaded');
            
            // Check if we have custom shirt IDs
            if (typeof customShirtProductIds !== 'undefined' && customShirtProductIds.length > 0) {
                console.log('Found custom shirts, processing cart items...');
                
                setTimeout(function() {
                    $('.woocommerce-cart-form .cart_item').each(function() {
                        var $cartItem = $(this);
                        
                        // Get product link to extract product ID
                        var $productLink = $cartItem.find('td[data-title="Product"] a, .product-name a').first();
                        var productUrl = $productLink.attr('href');
                        
                        if (productUrl) {
                            // Extract product ID from URL (common patterns)
                            var productId = null;
                            
                            // Try different URL patterns
                            var idMatch = productUrl.match(/product_id=(\d+)/);
                            if (!idMatch) {
                                idMatch = productUrl.match(/\/(\d+)\/?$/);
                            }
                            if (!idMatch) {
                                // Look for data attribute
                                productId = $productLink.data('product_id') || $cartItem.find('[data-product_id]').data('product_id');
                            } else {
                                productId = parseInt(idMatch[1]);
                            }
                            
                            console.log('Cart item product ID:', productId, 'Custom shirt IDs:', customShirtProductIds);
                            
                            // Check if this product ID is in our custom shirt list
                            if (productId && customShirtProductIds.includes(parseInt(productId))) {
                                console.log('Disabling quantity for custom shirt product ID:', productId);
                                
                                var $quantityInput = $cartItem.find('.quantity input[type="number"]');
                                
                                if ($quantityInput.length) {
                                    $quantityInput.prop('readonly', true);
                                    $quantityInput.css({
                                        'background-color': '#f5f5f5',
                                        'cursor': 'not-allowed',
                                        'border': '1px solid #ddd'
                                    });
                                    
                                    $cartItem.find('.quantity .plus, .quantity .minus, .qty-btn').hide();
                                    
                                    if (!$cartItem.find('.custom-shirt-notice').length) {
                                        $quantityInput.after('<br><small class="custom-shirt-notice" style="color: #666; font-style: italic;">כמות נקבעת לפי מידות שנבחרו</small>');
                                    }
                                    
                                    console.log('Successfully disabled quantity for custom shirt');
                                }
                            } else {
                                console.log('Regular product - quantity remains editable');
                            }
                        }
                    });
                }, 1000);
            } else {
                console.log('No custom shirts in cart');
            }
        });
        </script>
        <?php
    }
}
add_action('wp_footer', 'disable_custom_shirt_quantity_in_cart', 10);

/**************************סוף ביטול עדכון כמות בעגלה לחולצה  ***************************/

/**************************סוף הגדרת מינמום כמות למוצר ***************************/

/*  הוספת אישור למייל אישור הזמנת ללקוח  */
function add_note_to_all_order_emails( $order, $sent_to_admin, $plain_text, $email ) {
    if ( $email->id !== 'customer_processing_order' ) {
        return;
    }

    echo '<div style="background-color: #ffffff; padding: 20px; border: 5px solid #E2F0F3; border-radius: 10px; text-align: right; font-size: 16px; line-height: 1.8;">
            <strong>תודה על רכישתך!</strong><br>
            הזמנתך תגיע לכתובת שבחרת עד 7 ימי עסקים<br>
            מספר מעקב ישלח אליך כאשר החבילה תצא למשלוח.<br>
            <div style="font-size: 20px; font-style: italic; font-weight: bold; text-align: center; margin-top: 10px; color: #0056b3;">
                אנחנו כאן בשבילך – צוות פרומוטופ
            </div>
          </div>';
}
add_action( 'woocommerce_email_order_details', 'add_note_to_all_order_emails', 10, 4 );
/*  הוספת אישור למייל אישור הזמנה ללקוח סוף */

/***********    מידות   *****/

/***********    סוף מידות    *****/

/****          סידור מידות בשלשות        *****/
// Add Size Fields Organizer Script - Variable Product Compatible (Only when min-qty > 0) - WITH VALUE SYNC

/******* start copy X1X1 *************/
// Add Size Fields Organizer Script - FIXED to not interfere with images

function add_size_fields_organizer_script() {
    if (is_product()) {
        global $product;
        
        $min_qty_field = get_post_meta($product->get_id(), 'product-min-qty-to-all-size', true);
        if (empty($min_qty_field) || intval($min_qty_field) <= 0) {
            return;
        }
        ?>
        <script>
        jQuery(document).ready(function($) {
            console.log('Clean size organization starting...');
            
            setTimeout(function() {
                // Hide all original size fields first
                $('.s_small, .s_medium, .s_large, .s_extra, .s_xxl, .s_3xl, .s_4xl, .s_4, .s_6, .s_8, .s_10, .s_12, .s_14, .s_16, .s_18').hide();
                
                // Find the parent container
                var $container = $('.s_small').parent();
                if ($container.length === 0) {
                    console.log('Container not found');
                    return;
                }
                
                // Create organized structure
                var $organized = $('<div class="clean-size-grid"></div>');
                
                // Row 1: S, M, L, XL, 2XL
                var $row1 = $('<div class="size-row"><div class="row-label">Adult Sizes:</div></div>');
                ['.s_small', '.s_medium', '.s_large', '.s_extra', '.s_xxl'].forEach(function(cls) {
                    var $field = $(cls);
                    if ($field.length > 0) {
                        var $clone = $field.clone(true);
                        $row1.append($clone);
                        // Sync values
                        $clone.find('input').on('input change keyup', function() {
                            $field.find('input').val($(this).val()).trigger('change');
                        });
                    }
                });
                
                // Row 2: 3XL, 4XL, 4, 6, 8
                var $row2 = $('<div class="size-row"><div class="row-label">Extended Sizes:</div></div>');
                ['.s_3xl', '.s_4xl', '.s_4', '.s_6', '.s_8'].forEach(function(cls) {
                    var $field = $(cls);
                    if ($field.length > 0) {
                        var $clone = $field.clone(true);
                        $row2.append($clone);
                        // Sync values
                        $clone.find('input').on('input change keyup', function() {
                            $field.find('input').val($(this).val()).trigger('change');
                        });
                    }
                });
                
                // Row 3: 10, 12, 14, 16, 18
                var $row3 = $('<div class="size-row"><div class="row-label">Youth Sizes:</div></div>');
                ['.s_10', '.s_12', '.s_14', '.s_16', '.s_18'].forEach(function(cls) {
                    var $field = $(cls);
                    if ($field.length > 0) {
                        var $clone = $field.clone(true);
                        $row3.append($clone);
                        // Sync values
                        $clone.find('input').on('input change keyup', function() {
                            $field.find('input').val($(this).val()).trigger('change');
                        });
                    }
                });
                
                // Add rows to organized container
                $organized.append($row1, $row2, $row3);
                
                // Add to page
                $container.append($organized);
                
                console.log('Clean organization complete');
            }, 2000);
        });
        </script>
        
        <style>
        .clean-size-grid {
            margin: 20px 0;
            clear: both;
            background: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
        }
        
        .clean-size-grid .size-row {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: flex-end;
            flex-wrap: wrap;
        }
        
        .clean-size-grid .row-label {
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            width: 100%;
            font-size: 14px;
        }
        
        .clean-size-grid .size-row > div:not(.row-label) {
            flex: 1 1 calc(20% - 12px);
            min-width: 100px;
            max-width: 140px;
        }
        
        .clean-size-grid input {
            width: 100% !important;
            text-align: center !important;
            padding: 8px !important;
            border: 2px solid #ddd !important;
            border-radius: 4px !important;
            font-size: 16px !important;
        }
        
        .clean-size-grid label {
            display: block !important;
            text-align: center !important;
            font-weight: bold !important;
            margin-bottom: 5px !important;
            color: #555 !important;
        }
        
        /* Mobile responsive */
        @media (max-width: 768px) {
            .clean-size-grid .size-row > div:not(.row-label) {
                flex: 1 1 calc(33.33% - 10px);
                min-width: 80px;
            }
        }
        
        @media (max-width: 480px) {
            .clean-size-grid .size-row > div:not(.row-label) {
                flex: 1 1 calc(50% - 10px);
                min-width: 70px;
            }
        }
        </style>
        <?php
    }
}
add_action('wp_footer', 'add_size_fields_organizer_script');

// REPLACE THIS FUNCTION: add_quantity_calculator_script()
function add_quantity_calculator_script() {
    if (is_product()) {
        global $product;
        
        $min_qty_field = get_post_meta($product->get_id(), 'product-min-qty-to-all-size', true);
        if (empty($min_qty_field) || intval($min_qty_field) <= 0) {
            return;
        }
        
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            console.log('Quantity calculator loaded - DIRECT FIELDS VERSION');
            
            // Look for ALL size field inputs directly (both original and cloned)
            var sizeFieldSelectors = [
                '.s_small input[type="number"], .s_small input[type="text"]',
                '.s_medium input[type="number"], .s_medium input[type="text"]', 
                '.s_large input[type="number"], .s_large input[type="text"]',
                '.s_extra input[type="number"], .s_extra input[type="text"]',
                '.s_xxl input[type="number"], .s_xxl input[type="text"]',
                '.s_3xl input[type="number"], .s_3xl input[type="text"]',
                '.s_4xl input[type="number"], .s_4xl input[type="text"]',
                '.s_4 input[type="number"], .s_4 input[type="text"]',
                '.s_6 input[type="number"], .s_6 input[type="text"]',
                '.s_8 input[type="number"], .s_8 input[type="text"]',
                '.s_10 input[type="number"], .s_10 input[type="text"]',
                '.s_12 input[type="number"], .s_12 input[type="text"]',
                '.s_14 input[type="number"], .s_14 input[type="text"]',
                '.s_16 input[type="number"], .s_16 input[type="text"]',
                '.s_18 input[type="number"], .s_18 input[type="text"]'
            ].join(', ');
            
            function calculateTotalQuantity() {
                var totalQty = 0;
                var sizeDetails = [];
                
                $(sizeFieldSelectors).each(function() {
                    var value = parseInt($(this).val()) || 0;
                    if (value > 0) {
                        totalQty += value;
                        
                        var $parent = $(this).closest('[class*="s_"]');
                        var sizeClass = $parent.attr('class');
                        var sizeName = '';
                        
                        if (sizeClass.includes('s_small')) sizeName = 'S';
                        else if (sizeClass.includes('s_medium')) sizeName = 'M';
                        else if (sizeClass.includes('s_large')) sizeName = 'L';
                        else if (sizeClass.includes('s_extra')) sizeName = 'XL';
                        else if (sizeClass.includes('s_xxl')) sizeName = '2XL';
                        else if (sizeClass.includes('s_3xl')) sizeName = '3XL';
                        else if (sizeClass.includes('s_4xl')) sizeName = '4XL';
                        else if (sizeClass.includes('s_4')) sizeName = '4';
                        else if (sizeClass.includes('s_6')) sizeName = '6';
                        else if (sizeClass.includes('s_8')) sizeName = '8';
                        else if (sizeClass.includes('s_10')) sizeName = '10';
                        else if (sizeClass.includes('s_12')) sizeName = '12';
                        else if (sizeClass.includes('s_14')) sizeName = '14';
                        else if (sizeClass.includes('s_16')) sizeName = '16';
                        else if (sizeClass.includes('s_18')) sizeName = '18';
                        
                        if (sizeName) {
                            sizeDetails.push(sizeName + ': ' + value);
                        }
                    }
                });
                
                console.log('Total quantity calculated: ' + totalQty);
                console.log('Size breakdown: ' + sizeDetails.join(', '));
                
                return {
                    total: totalQty,
                    details: sizeDetails
                };
            }
            
            function updateMainQuantity() {
                var result = calculateTotalQuantity();
                
                var $mainQtyInput = $('input[name="quantity"], .qty, input.qty');
                if ($mainQtyInput.length > 0) {
                    $mainQtyInput.val(result.total);
                    console.log('Updated main quantity to: ' + result.total);
                    $mainQtyInput.trigger('change');
                }
            }
            
            // Attach listeners to ALL size fields
            $(document).on('input change keyup', sizeFieldSelectors, function() {
                console.log('Size field changed: ' + $(this).val());
                updateMainQuantity();
            });
            
            // Prevent form submission if no sizes selected
            $('form.cart').on('submit', function(e) {
                var result = calculateTotalQuantity();
                if (result.total === 0) {
                    e.preventDefault();
                    alert('אנא בחר כמות לפחות מידה אחת');
                    return false;
                }
            });
            
            // Initial calculation
            setTimeout(updateMainQuantity, 1000);
        });
        </script>
        <?php
    }
}


/**** min - qty for shirts  ****/
// Safe supplementary validation for shirt products only
function shirt_size_validation_supplement() {
    if (is_product()) {
        global $product;
        
        // Only run for products that have the shirt size field
        $min_qty_field = get_post_meta($product->get_id(), 'product-min-qty-to-all-size', true);
        if (empty($min_qty_field) || intval($min_qty_field) <= 0) {
            return; // Skip - not a shirt product
        }
        ?>
        <script>
        jQuery(document).ready(function($) {
            console.log('Shirt supplement validation loaded');
            
            // Only override form submission for shirt products
            $('form.cart').off('submit.shirtvalidation').on('submit.shirtvalidation', function(e) {
                var shirtTotal = 0;
                
                // Look specifically for shirt size inputs
                var sizeClasses = ['s_small', 's_medium', 's_large', 's_extra', 's_xxl', 's_3xl', 's_4xl', 's_4', 's_6', 's_8', 's_10', 's_12', 's_14', 's_16', 's_18'];
                
                sizeClasses.forEach(function(className) {
                    $('.' + className + ' input[type="number"]').each(function() {
                        var val = parseInt($(this).val()) || 0;
                        if (val > 0) {
                            shirtTotal += val;
                            console.log('Shirt size found:', className, '=', val);
                        }
                    });
                });
                
                console.log('Shirt total:', shirtTotal);
                
                if (shirtTotal > 0) {
                    // Update main quantity for shirt
                    $('input[name="quantity"]').val(shirtTotal);
                    console.log('Updated main quantity to:', shirtTotal);
                }
            });
        });
        </script>
        <?php
    }
}
add_action('wp_footer', 'shirt_size_validation_supplement', 25);


/******* end copy X1X1 *************/

add_action('wp_footer', 'add_quantity_calculator_script');

/******     סוף    חישוב כמות יחידות מוצר לחולצה עם מידות - חיבור השדות המידות    ******/
/******     product-min-qty-to-all-size        חישוב כמות מינימום לחולצה עם מידות      ******/
// Add Minimum Quantity Validation Script (Only when min-qty > 0)
function add_min_quantity_validation_script() {
    // Only load on product pages
    if (is_product()) {
        global $product;
        
        // Get the minimum quantity from JetEngine custom field
        $min_qty = get_post_meta($product->get_id(), 'product-min-qty-to-all-size', true);
        
        // Only run if field exists, is numeric, and greater than 0
        if (!empty($min_qty) && is_numeric($min_qty) && intval($min_qty) > 0) {
            ?>
            <script type="text/javascript">
            jQuery(document).ready(function($) {
                console.log('Minimum quantity validation loaded - Min required: <?php echo $min_qty; ?>');
                
                var minRequiredQty = <?php echo intval($min_qty); ?>;
                
                // Function to show minimum quantity message
                function showMinQtyMessage() {
                    var messageId = 'min-qty-message';
                    var $existingMessage = $('#' + messageId);
                    
                    if ($existingMessage.length === 0) {
                        var messageHtml = '<div id="' + messageId + '" style="' +
                            'margin: 10px 0; ' +
                            'padding: 12px 15px; ' +
                            'background: #f8d7da; ' +
                            'color: #721c24; ' +
                            'border: 1px solid #f5c6cb; ' +
                            'border-radius: 5px; ' +
                            'font-weight: bold; ' +
                            'text-align: center;' +
                            '">' +
                            'כמות מינימלית להזמנה: ' + minRequiredQty + ' יחידות' +
                            '</div>';
                        
                        // Insert before quantity display or add to cart button
                        var $quantityDisplay = $('#total-quantity-display');
                        var $addToCartBtn = $('.single_add_to_cart_button');
                        
                        if ($quantityDisplay.length > 0) {
                            $quantityDisplay.before(messageHtml);
                        } else if ($addToCartBtn.length > 0) {
                            $addToCartBtn.before(messageHtml);
                        }
                    }
                }
                
                // Function to hide minimum quantity message
                function hideMinQtyMessage() {
                    $('#min-qty-message').remove();
                }
                
                // Function to validate minimum quantity
                function validateMinQuantity() {
                    // Size field selectors (same as quantity calculator)
                  var sizeFieldSelectors = [
                   '.organized-size-fields .s_small input[type="number"], .organized-size-fields .s_small input[type="text"]',
                   '.organized-size-fields .s_medium input[type="number"], .organized-size-fields .s_medium input[type="text"]',
                   '.organized-size-fields .s_large input[type="number"], .organized-size-fields .s_large input[type="text"]',
                   '.organized-size-fields .s_extra input[type="number"], .organized-size-fields .s_extra input[type="text"]',
                   '.organized-size-fields .s_xxl input[type="number"], .organized-size-fields .s_xxl input[type="text"]',
                   '.organized-size-fields .s_xxxxl input[type="number"], .organized-size-fields .s_xxxxl input[type="text"]',
                   '.organized-size-fields .s_14 input[type="number"], .organized-size-fields .s_14 input[type="text"]',
                   '.organized-size-fields .s_16 input[type="number"], .organized-size-fields .s_16 input[type="text"]',
                   '.organized-size-fields .s_18 input[type="number"], .organized-size-fields .s_18 input[type="text"]'
                ].join(', ');
                  
                /*    var sizeFieldSelectors = [
                        '.s_small input[type="number"], .s_small input[type="text"]',
                        '.s_medium input[type="number"], .s_medium input[type="text"]', 
                        '.s_large input[type="number"], .s_large input[type="text"]',
                        '.s_extra input[type="number"], .s_extra input[type="text"]',
                        '.s_xxl input[type="number"], .s_xxl input[type="text"]',
                        '.s_xxxxl input[type="number"], .s_xxxxl input[type="text"]',
                        '.s_14 input[type="number"], .s_14 input[type="text"]',
                        '.s_16 input[type="number"], .s_16 input[type="text"]',
                        '.s_18 input[type="number"], .s_18 input[type="text"]'
                    ].join(', ');
                    */
                    
                    var totalQty = 0;
                    
                    // Calculate total quantity
                    $(sizeFieldSelectors).each(function() {
                        var value = parseInt($(this).val()) || 0;
                        totalQty += value;
                    });
                    
                    console.log('Validating - Total: ' + totalQty + ', Min Required: ' + minRequiredQty);
                    
                    if (totalQty > 0 && totalQty < minRequiredQty) {
                        showMinQtyMessage();
                        return false;
                    } else {
                        hideMinQtyMessage();
                        return true;
                    }
                }
                
                // Function to update quantity display with minimum info
                function updateQuantityDisplayWithMin(result) {
                    var displayId = 'total-quantity-display';
                    var $display = $('#' + displayId);
                    
                    if ($display.length > 0) {
                        var $totalSpan = $('#total-qty-number');
                        var currentQty = result ? result.total : 0;
                        
                        // Update color based on minimum requirement
                        if (currentQty >= minRequiredQty) {
                            $totalSpan.css('color', '#28a745'); // Green
                            hideMinQtyMessage();
                        } else if (currentQty > 0) {
                            $totalSpan.css('color', '#dc3545'); // Red
                            showMinQtyMessage();
                        } else {
                            $totalSpan.css('color', '#333'); // Default
                            hideMinQtyMessage();
                        }
                        
                        // Add minimum info to display
                        var $minInfo = $('#min-qty-info');
                        if ($minInfo.length === 0) {
                            $display.append('<div id="min-qty-info" style="font-size: 12px; color: #666; margin-top: 5px;">מינימום: ' + minRequiredQty + ' יחידות</div>');
                        }
                    }
                }
                
                // Override the original updateQuantityDisplay function
                window.originalCalculateTotalQuantity = window.calculateTotalQuantity || function() { return {total: 0, details: []}; };
                
                // Enhanced quantity calculation with minimum validation
                function enhancedQuantityUpdate() {
                    // Use the existing calculation logic
                  var sizeFieldSelectors = [
                    '.organized-size-fields .s_small input[type="number"], .organized-size-fields .s_small input[type="text"]',
                    '.organized-size-fields .s_medium input[type="number"], .organized-size-fields .s_medium input[type="text"]',
                    '.organized-size-fields .s_large input[type="number"], .organized-size-fields .s_large input[type="text"]',
                    '.organized-size-fields .s_extra input[type="number"], .organized-size-fields .s_extra input[type="text"]',
                    '.organized-size-fields .s_xxl input[type="number"], .organized-size-fields .s_xxl input[type="text"]',
                    '.organized-size-fields .s_xxxxl input[type="number"], .organized-size-fields .s_xxxxl input[type="text"]',
                    '.organized-size-fields .s_14 input[type="number"], .organized-size-fields .s_14 input[type="text"]',
                    '.organized-size-fields .s_16 input[type="number"], .organized-size-fields .s_16 input[type="text"]',
                    '.organized-size-fields .s_18 input[type="number"], .organized-size-fields .s_18 input[type="text"]'
                  ].join(', ');    
                  
                    var totalQty = 0;
                    var sizeDetails = [];
                    
                    $(sizeFieldSelectors).each(function() {
                        var value = parseInt($(this).val()) || 0;
                        if (value > 0) {
                            totalQty += value;
                            
                            var $parent = $(this).closest('[class*="s_"]');
                            var sizeClass = $parent.attr('class');
                            var sizeName = '';
                            
                            if (sizeClass.includes('s_small')) sizeName = 'S';
                            else if (sizeClass.includes('s_medium')) sizeName = 'M';
                            else if (sizeClass.includes('s_large')) sizeName = 'L';
                            else if (sizeClass.includes('s_extra')) sizeName = 'XL';
                            else if (sizeClass.includes('s_xxl')) sizeName = '2XL';
                            else if (sizeClass.includes('s_xxxxl')) sizeName = '4XL';
                            else if (sizeClass.includes('s_14')) sizeName = '14';
                            else if (sizeClass.includes('s_16')) sizeName = '16';
                            else if (sizeClass.includes('s_18')) sizeName = '18';
                            
                            if (sizeName) {
                                sizeDetails.push(sizeName + ': ' + value);
                            }
                        }
                    });
                    
                    var result = {
                        total: totalQty,
                        details: sizeDetails
                    };
                    
                    // Update display with minimum validation
                    updateQuantityDisplayWithMin(result);
                    
                    return result;
                }
                
                // Attach listeners for minimum validation
                function attachMinValidationListeners() {
                  var sizeFieldSelectors = [
                      '.organized-size-fields .s_small input[type="number"], .organized-size-fields .s_small input[type="text"]',
                      '.organized-size-fields .s_medium input[type="number"], .organized-size-fields .s_medium input[type="text"]',
                      '.organized-size-fields .s_large input[type="number"], .organized-size-fields .s_large input[type="text"]',
                      '.organized-size-fields .s_extra input[type="number"], .organized-size-fields .s_extra input[type="text"]',
                      '.organized-size-fields .s_xxl input[type="number"], .organized-size-fields .s_xxl input[type="text"]',
                      '.organized-size-fields .s_xxxxl input[type="number"], .organized-size-fields .s_xxxxl input[type="text"]',
                      '.organized-size-fields .s_14 input[type="number"], .organized-size-fields .s_14 input[type="text"]',
                      '.organized-size-fields .s_16 input[type="number"], .organized-size-fields .s_16 input[type="text"]',
                      '.organized-size-fields .s_18 input[type="number"], .organized-size-fields .s_18 input[type="text"]'
                  ].join(', '); 
                  
                    $(document).off('input.minvalidation change.minvalidation', sizeFieldSelectors);
                    $(document).on('input.minvalidation change.minvalidation', sizeFieldSelectors, function() {
                        enhancedQuantityUpdate();
                    });
                }
                
                // Enhanced form submission validation
                $('form.cart').off('submit.minvalidation').on('submit.minvalidation', function(e) {
                    if (!validateMinQuantity()) {
                        e.preventDefault();
                        alert('כמות מינימלית להזמנה היא ' + minRequiredQty + ' יחידות');
                        return false;
                    }
                });
                
                // Initialize minimum validation
                setTimeout(function() {
                    attachMinValidationListeners();
                    enhancedQuantityUpdate();
                }, 1000);
                
                // Re-initialize on variation changes
                $(document).on('found_variation reset_data', function() {
                    setTimeout(function() {
                        attachMinValidationListeners();
                        enhancedQuantityUpdate();
                    }, 500);
                });
            });
            </script>
            <?php
        }
    }
}
add_action('wp_footer', 'add_min_quantity_validation_script', 15);

/******     product-min-qty-to-all-size        חישוב כמות מינימום לחולצה עם מידות      ******/

/******     עדכון סה"כ יחידות      *****/
// Step 6: COMPLETE - Override WooCommerce quantity with size summary (Only when min-qty > 0)
function override_quantity_with_size_summary() {
    if (is_product()) {
        global $product;
        
        // Check if product has the min-qty field set AND greater than 0
        $min_qty_field = get_post_meta($product->get_id(), 'product-min-qty-to-all-size', true);
        
        // Only run if the field exists and has a value greater than 0
        if (empty($min_qty_field) || intval($min_qty_field) <= 0) {
            return; // Skip for products without min-qty > 0
        }
        
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            console.log('Step 6: Quantity override loaded for product with min-qty > 0');
            
            // Size field selectors
          var sizeFieldSelectors = [
             '.organized-size-fields .s_small input[type="number"], .organized-size-fields .s_small input[type="text"]',
             '.organized-size-fields .s_medium input[type="number"], .organized-size-fields .s_medium input[type="text"]',
             '.organized-size-fields .s_large input[type="number"], .organized-size-fields .s_large input[type="text"]',
             '.organized-size-fields .s_extra input[type="number"], .organized-size-fields .s_extra input[type="text"]',
             '.organized-size-fields .s_xxl input[type="number"], .organized-size-fields .s_xxl input[type="text"]',
             '.organized-size-fields .s_xxxxl input[type="number"], .organized-size-fields .s_xxxxl input[type="text"]',
             '.organized-size-fields .s_14 input[type="number"], .organized-size-fields .s_14 input[type="text"]',
             '.organized-size-fields .s_16 input[type="number"], .organized-size-fields .s_16 input[type="text"]',
             '.organized-size-fields .s_18 input[type="number"], .organized-size-fields .s_18 input[type="text"]'
            
             ].join(', ');
            
            // Function to calculate and update main quantity
            function updateMainQuantity() {
                var totalQty = 0;
                
                // Sum all size quantities
                $(sizeFieldSelectors).each(function() {
                    var value = parseInt($(this).val()) || 0;
                    totalQty += value;
                });
                
                // Find and update WooCommerce main quantity field
                var $mainQty = $('input[name="quantity"], .qty, input.qty');
                if ($mainQty.length > 0) {
                    $mainQty.val(totalQty);
                    console.log('Step 6: Updated main quantity to: ' + totalQty);
                }
                
                return totalQty;
            }
            
            // Attach listeners to size fields
            function attachListeners() {
                $(document).off('input.step6 change.step6', sizeFieldSelectors);
                $(document).on('input.step6 change.step6 keyup.step6', sizeFieldSelectors, function() {
                    updateMainQuantity();
                });
            }
            
            // Initialize
            function initStep6() {
                setTimeout(function() {
                    if ($(sizeFieldSelectors).length > 0) {
                        console.log('Step 6: Size fields found, attaching quantity updater');
                        attachListeners();
                        updateMainQuantity(); // Set initial value
                    } else {
                        console.log('Step 6: Size fields not found yet, retrying...');
                        setTimeout(initStep6, 1000);
                    }
                }, 1000);
            }
            
            // Start initialization
            initStep6();
            
            // Re-initialize on variation changes
            $(document).on('found_variation reset_data woocommerce_update_variation_values', function() {
                setTimeout(initStep6, 800);
            });
        });
        </script>
        <?php
    }
}
add_action('wp_footer', 'override_quantity_with_size_summary', 30);

/********   עדכון סה"כ יחידות סוף  ************/

/*********  עיצוב רישום הכמויות בעגלה     ************/ 
// Style cart size details for custom shirts - IMPROVED LAYOUT
// Style cart size details for custom shirts - FINAL FIX for split DD elements
// Style cart size details for custom shirts - CORRECTED for DT/DD structure
function style_cart_size_details() {
    if (is_cart() || is_checkout() || wp_doing_ajax()) {
        ?>
        <style>
        /* Style for cart size details - Compact horizontal layout */
        .cart-item-sizes {
            margin: 6px 0 !important;
            padding: 8px 10px !important;
            background: #f8f9fa !important;
            border-left: 3px solid #007cba !important;
            border-radius: 0 4px 4px 0 !important;
            font-size: 13px !important;
            line-height: 1.3 !important;
            display: block !important;
            clear: both !important;
        }
        
        .cart-item-sizes .size-title {
            font-weight: bold !important;
            color: #495057 !important;
            margin-bottom: 4px !important;
            display: block !important;
            font-size: 14px !important;
        }
        
        .cart-item-sizes .size-items-container {
            display: flex !important;
            flex-wrap: wrap !important;
            gap: 8px 12px !important;
            align-items: center !important;
        }
        
        .cart-item-sizes .size-item {
            display: inline-flex !important;
            align-items: center !important;
            padding: 2px 6px !important;
            background: white !important;
            border: 1px solid #dee2e6 !important;
            border-radius: 3px !important;
            color: #495057 !important;
            font-size: 12px !important;
            white-space: nowrap !important;
        }
        
        .cart-item-sizes .size-name {
            font-weight: 600 !important;
            color: #343a40 !important;
            margin-left: 2px !important;
        }
        
        .cart-item-sizes .size-quantity {
            color: #007cba !important;
            font-weight: bold !important;
            margin-right: 2px !important;
        }
        
        /* Hide original variation data when we add custom formatting */
        .cart_item[data-has-custom-sizes="true"] .variation {
            display: none !important;
        }
        
        /* Widget cart specific styles */
        .widget_shopping_cart .cart-item-sizes {
            font-size: 11px !important;
            padding: 5px 8px !important;
            margin: 4px 0 !important;
        }
        
        .widget_shopping_cart .cart-item-sizes .size-title {
            font-size: 12px !important;
            margin-bottom: 3px !important;
        }
        
        .widget_shopping_cart .cart-item-sizes .size-items-container {
            gap: 4px 8px !important;
        }
        
        .widget_shopping_cart .cart-item-sizes .size-item {
            padding: 1px 4px !important;
            font-size: 11px !important;
        }
        
        /* Mobile responsiveness */
        @media (max-width: 768px) {
            .cart-item-sizes .size-items-container {
                flex-direction: column !important;
                align-items: flex-start !important;
                gap: 4px !important;
            }
            
            .cart-item-sizes .size-item {
                margin: 1px 0 !important;
            }
        }
        </style>
        
        <script>
        jQuery(document).ready(function($) {
            console.log('Cart size styling script loaded - DT/DD VERSION');
            
            function formatSizeDetails() {
                console.log('Running formatSizeDetails function');
                
                // Process cart items
                $('.cart_item, .mini_cart_item').each(function() {
                    var $cartItem = $(this);
                    
                    // Check if this cart item already has custom size formatting
                    if ($cartItem.find('.cart-item-sizes').length > 0) {
                        return; // Skip if already formatted
                    }
                    
                    // Look for variation dt elements (these contain the size names)
                    var $variationDts = $cartItem.find('dl.variation dt, .variation dt');
                    console.log('Found variation DT elements:', $variationDts.length);
                    
                    if ($variationDts.length === 0) {
                        return; // No variation data found
                    }
                    
                    var sizeData = [];
                    
                    // Process each dt element
                    $variationDts.each(function() {
                        var $dt = $(this);
                        var dtText = $dt.text().trim();
                        console.log('Processing DT:', dtText);
                        
                        // Look for size patterns in dt text (remove colon if present)
                        var sizeName = dtText.replace(':', '').trim();
                        var sizePattern = /^(S|M|L|XL|XXL|XXXL|XXXXL|2XL|3XL|4XL|14|16|18)$/;
                        
                        if (sizePattern.test(sizeName)) {
                            // Find the corresponding dd element
                            var $dd = $dt.next('dd');
                            if ($dd.length > 0) {
                                var quantity = $dd.text().trim();
                                console.log('Found size:', sizeName, 'quantity:', quantity);
                                
                                // Only add if quantity is a number and > 0
                                if (/^\d+$/.test(quantity) && parseInt(quantity) > 0) {
                                    sizeData.push({
                                        size: sizeName,
                                        quantity: quantity
                                    });
                                    console.log('Added to sizeData:', sizeName, '=', quantity);
                                }
                            }
                        }
                    });
                    
                    // If we found size data, format it
                    if (sizeData.length > 0) {
                        console.log('Processing', sizeData.length, 'sizes for formatting');
                        
                        // Mark this cart item as having custom sizes
                        $cartItem.attr('data-has-custom-sizes', 'true');
                        
                        // Create formatted HTML
                        var formattedHtml = '<div class="cart-item-sizes">';
                        formattedHtml += '<span class="size-title"> כמות עבור כל מידה:</span>';
                        formattedHtml += '<div class="size-items-container">';
                        
                        $.each(sizeData, function(index, item) {
                            formattedHtml += '<div class="size-item">';
                            formattedHtml += '<span class="size-name">' + item.size + '</span>=';
                            formattedHtml += '<span class="size-quantity">' + item.quantity + '</span>';
                            formattedHtml += '</div>';
                        });
                        
                        formattedHtml += '</div></div>';
                        
                        // Insert the formatted sizes after the product name
                        var $productCell = $cartItem.find('td.product-name, .product-name').first();
                        if ($productCell.length > 0) {
                            $productCell.append(formattedHtml);
                            console.log('Added formatted sizes to product cell');
                        } else {
                            // Fallback: add after the variation
                            $cartItem.find('.variation').after(formattedHtml);
                            console.log('Added formatted sizes after variation (fallback)');
                        }
                    } else {
                        console.log('No valid size data found for this cart item');
                    }
                });
            }
            
            // Format sizes on page load with multiple attempts
            function initFormatting() {
                setTimeout(formatSizeDetails, 500);
                setTimeout(formatSizeDetails, 1500);
                setTimeout(formatSizeDetails, 3000);
            }
            
            // Run on page load
            initFormatting();
            
            // Re-format when cart updates
            $(document.body).on('updated_cart_totals updated_checkout wc_cart_emptied', function() {
                console.log('Cart updated, reformatting sizes');
                // Clear existing formatted sizes first
                $('.cart-item-sizes').remove();
                $('.cart_item').removeAttr('data-has-custom-sizes');
                setTimeout(formatSizeDetails, 1000);
            });
            
            // For AJAX cart updates
            $(document.body).on('added_to_cart removed_from_cart', function() {
                console.log('Cart item added/removed, reformatting sizes');
                $('.cart-item-sizes').remove();
                $('.cart_item').removeAttr('data-has-custom-sizes');
                setTimeout(formatSizeDetails, 1500);
            });
            
            // Manual trigger for testing
            window.formatCartSizes = formatSizeDetails;
            window.clearCartSizes = function() {
                $('.cart-item-sizes').remove();
                $('.cart_item').removeAttr('data-has-custom-sizes');
                console.log('Cleared all size formatting');
            };
        });
        </script>
        <?php
    }
}
add_action('wp_footer', 'style_cart_size_details');
add_action('wp_head', 'style_cart_size_details');

/*********  עיצוב רישום הכמויות בעגלה   סוף  ************/

/***********  עיצוב עמוד תודה סידור פירוט כמויות למוצר נרכש ***************/
// Style size details on thank you page and order details
// Simple universal styling for thank you page sizes
function simple_thankyou_page_sizes() {
    // Run on thank you pages, account pages, and any page that might show order details
    ?>
    <style>
    /* Universal thank you page size styling */
    .formatted-order-sizes {
        margin: 8px 0 !important;
        padding: 8px 12px !important;
        background: #f8f9fa !important;
        border-left: 3px solid #007cba !important;
        border-radius: 0 4px 4px 0 !important;
        font-size: 13px !important;
        line-height: 1.4 !important;
    }
    
    .formatted-order-sizes .sizes-title {
        font-weight: bold !important;
        color: #495057 !important;
        margin-bottom: 5px !important;
        display: block !important;
    }
    
    .formatted-order-sizes .sizes-list {
        display: flex !important;
        flex-wrap: wrap !important;
        gap: 6px 10px !important;
    }
    
    .formatted-order-sizes .size-badge {
        display: inline-flex !important;
        align-items: center !important;
        padding: 2px 6px !important;
        background: white !important;
        border: 1px solid #dee2e6 !important;
        border-radius: 3px !important;
        font-size: 12px !important;
        color: #495057 !important;
    }
    
    .formatted-order-sizes .size-name {
        font-weight: 600 !important;
        color: #343a40 !important;
    }
    
    .formatted-order-sizes .size-qty {
        color: #007cba !important;
        font-weight: bold !important;
        margin-right: 2px !important;
    }
    
    /* Hide original messy size display when formatted */
    .size-formatted + * {
        display: none !important;
    }
    
    /* Mobile responsive */
    @media (max-width: 768px) {
        .formatted-order-sizes .sizes-list {
            flex-direction: column !important;
            gap: 3px !important;
        }
    }
    </style>
    
    <script>
    jQuery(document).ready(function($) {
        console.log('Simple thank you page formatting loaded');
        
        function formatOrderSizes() {
            console.log('Looking for size patterns to format...');
            
            // Look for any text that contains size patterns
            $('*').contents().filter(function() {
                return this.nodeType === 3; // Text nodes only
            }).each(function() {
                var text = this.textContent.trim();
                
                // Skip if already processed or parent already has formatted sizes
                if ($(this).parent().hasClass('size-formatted') || $(this).closest('.formatted-order-sizes').length > 0) {
                    return;
                }
                
                // Look for size patterns like "S:", "M:", "16:", etc.
                if (/^(S|M|L|XL|XXL|XXXL|XXXXL|2XL|3XL|4XL|14|16|18):?$/.test(text)) {
                    var sizeName = text.replace(':', '').trim();
                    var $currentElement = $(this).parent();
                    
                    // Look for the next element that might contain a quantity
                    var $nextElements = $currentElement.nextAll().slice(0, 3); // Check next 3 elements
                    var quantity = null;
                    
                    $nextElements.each(function() {
                        var nextText = $(this).text().trim();
                        if (/^\d+$/.test(nextText) && parseInt(nextText) > 0) {
                            quantity = nextText;
                            return false; // Break the loop
                        }
                    });
                    
                    if (quantity) {
                        console.log('Found size:', sizeName, 'quantity:', quantity);
                        
                        // Mark elements as processed
                        $currentElement.addClass('size-formatted');
                        
                        // Create or find the sizes container
                        var $container = $currentElement.siblings('.formatted-order-sizes');
                        if ($container.length === 0) {
                            $container = $('<div class="formatted-order-sizes"><div class="sizes-title">מידות:</div><div class="sizes-list"></div></div>');
                            $currentElement.before($container);
                        }
                        
                        // Add this size to the container
                        var $sizesList = $container.find('.sizes-list');
                        var sizeHtml = '<div class="size-badge"><span class="size-name">' + sizeName + '</span>=<span class="size-qty">' + quantity + '</span></div>';
                        $sizesList.append(sizeHtml);
                        
                        // Hide the original elements
                        $currentElement.hide();
                        $nextElements.filter(function() {
                            return $(this).text().trim() === quantity;
                        }).first().hide();
                    }
                }
            });
            
            // Alternative method: Look for consecutive elements with size and number patterns
            $('*').each(function() {
                var $element = $(this);
                var text = $element.text().trim();
                
                // Skip if already processed
                if ($element.hasClass('size-formatted') || $element.closest('.formatted-order-sizes').length > 0) {
                    return;
                }
                
                // Check if this element contains a size pattern
                if (/^(S|M|L|XL|XXL|XXXL|XXXXL|2XL|3XL|4XL|14|16|18):?$/.test(text)) {
                    var sizeName = text.replace(':', '').trim();
                    var $nextElement = $element.next();
                    
                    if ($nextElement.length > 0) {
                        var nextText = $nextElement.text().trim();
                        if (/^\d+$/.test(nextText) && parseInt(nextText) > 0) {
                            var quantity = nextText;
                            
                            console.log('Found consecutive elements - Size:', sizeName, 'Quantity:', quantity);
                            
                            // Mark as processed
                            $element.addClass('size-formatted');
                            $nextElement.addClass('size-formatted');
                            
                            // Create formatted display
                            var formattedHtml = '<div class="formatted-order-sizes">';
                            formattedHtml += '<div class="sizes-title">מידות:</div>';
                            formattedHtml += '<div class="sizes-list">';
                            formattedHtml += '<div class="size-badge"><span class="size-name">' + sizeName + '</span>=<span class="size-qty">' + quantity + '</span></div>';
                            formattedHtml += '</div></div>';
                            
                            $element.before(formattedHtml);
                            $element.hide();
                            $nextElement.hide();
                        }
                    }
                }
            });
        }
        
        // Run formatting multiple times with delays
        setTimeout(formatOrderSizes, 1000);
        setTimeout(formatOrderSizes, 3000);
        setTimeout(formatOrderSizes, 5000);
        
        // Manual trigger for testing
        window.formatOrderSizes = formatOrderSizes;
        
        // Also try to format when page content changes
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length > 0) {
                    setTimeout(formatOrderSizes, 500);
                }
            });
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
    </script>
    <?php
}
add_action('wp_footer', 'simple_thankyou_page_sizes', 25);

/***********  עיצוב עמוד תודה סידור פירוט כמויות למוצר נרכש סוף ***************/

/************* ******************/
/*** Image Fix for Radio Button Changes ***********/
// Fix for image reset when radio buttons are clicked
function fix_color_image_persistence() {
    if (is_product()) {
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            console.log('🔧 Color Image Persistence Fix - LOADED');
            
            var currentVariationImage = null;
            var isVariationActive = false;
            
            // Store the current variation image when a color is selected
            $(document).on('found_variation', function(event, variation) {
                console.log('✅ Variation found - storing image');
                if (variation.image && variation.image.full_src) {
                    currentVariationImage = variation.image;
                    isVariationActive = true;
                    console.log('📷 Stored variation image:', currentVariationImage.full_src);
                }
            });
            
            // Clear stored image when variation is reset
            $(document).on('reset_data', function() {
                console.log('🔄 Variation reset');
                currentVariationImage = null;
                isVariationActive = false;
            });
            
            // Function to restore the variation image
            function restoreVariationImage() {
                if (currentVariationImage && isVariationActive) {
                    setTimeout(function() {
                        var $mainImage = $('.woocommerce-product-gallery__image img').first();
                        var currentSrc = $mainImage.attr('src');
                        
                        if (currentSrc !== currentVariationImage.full_src) {
                            console.log('🔄 Restoring variation image');
                            console.log('   From:', currentSrc);
                            console.log('   To:', currentVariationImage.full_src);
                            
                            // Update the main image
                            $mainImage.attr('src', currentVariationImage.full_src);
                            $mainImage.attr('srcset', currentVariationImage.srcset || '');
                            $mainImage.attr('sizes', currentVariationImage.sizes || '');
                            
                            // Update data attributes if they exist
                            if (currentVariationImage.title) {
                                $mainImage.attr('alt', currentVariationImage.title);
                                $mainImage.attr('title', currentVariationImage.title);
                            }
                            
                            // Update gallery wrapper data if it exists
                            var $galleryImage = $mainImage.closest('.woocommerce-product-gallery__image');
                            if ($galleryImage.length && currentVariationImage.full_src) {
                                $galleryImage.attr('data-thumb', currentVariationImage.gallery_thumbnail_src || currentVariationImage.thumb_src);
                            }
                        }
                    }, 100);
                }
            }
            
            // Monitor radio button changes specifically
            $(document).on('change', 'input[type="radio"]', function() {
                var $radio = $(this);
                console.log('📻 Radio button changed:', $radio.attr('name'), '=', $radio.val());
                
                // Restore image after radio button change
                restoreVariationImage();
                
                // Also restore after a short delay in case other scripts interfere
                setTimeout(restoreVariationImage, 500);
                setTimeout(restoreVariationImage, 1000);
            });
            
            // Monitor any field changes that might affect the image
            $(document).on('change', '.fpf-field input, .fpf-field select, .fpf-field textarea', function() {
                console.log('📝 Flexible Product Field changed');
                restoreVariationImage();
                setTimeout(restoreVariationImage, 300);
            });
            
            // Override any setTimeout calls that might reset the image
            var originalSetTimeout = window.setTimeout;
            window.setTimeout = function(callback, delay) {
                // If there's an active variation and this timeout might affect images
                if (isVariationActive && currentVariationImage && delay > 100 && delay < 5000) {
                    var callbackStr = callback.toString();
                    if (callbackStr.includes('src') || callbackStr.includes('image') || callbackStr.includes('gallery')) {
                        console.log('⚠️ Intercepting potentially harmful timeout');
                        
                        // Wrap the original callback to restore our image afterwards
                        var originalCallback = callback;
                        callback = function() {
                            var result = originalCallback.apply(this, arguments);
                            setTimeout(restoreVariationImage, 50);
                            return result;
                        };
                    }
                }
                return originalSetTimeout.apply(this, arguments);
            };
            
            // Monitor direct image changes and restore if needed
            var imageCheckInterval = setInterval(function() {
                if (isVariationActive && currentVariationImage) {
                    var $mainImage = $('.woocommerce-product-gallery__image img').first();
                    var currentSrc = $mainImage.attr('src');
                    
                    if (currentSrc && currentSrc !== currentVariationImage.full_src) {
                        // Check if this is an unwanted reset (not a new variation)
                        var isProductDefault = currentSrc.includes('product') && !currentSrc.includes('variation');
                        if (isProductDefault) {
                            console.log('🚨 Detected unwanted image reset, restoring...');
                            restoreVariationImage();
                        }
                    }
                }
            }, 2000); // Check every 2 seconds
            
            // Clean up interval when page unloads
            $(window).on('beforeunload', function() {
                if (imageCheckInterval) {
                    clearInterval(imageCheckInterval);
                }
            });
            
            // Manual restore function for testing
            window.restoreVariationImage = restoreVariationImage;
            window.getCurrentVariationImage = function() {
                return currentVariationImage;
            };
        });
        </script>
        <?php
    }
}
add_action('wp_footer', 'fix_color_image_persistence', 5);
/*** Image Fix End ***********/

/************    ***************/