# onwebchat/3.8.1/admin/tabs/woocommerce.php

AI Chatbot for WooCommerce &amp; Live Chat – onWebChat, version 3.8.1. 853 lines.

- Page: https://pluginprobe.com/plugins/onwebchat/3.8.1/code/admin/tabs/woocommerce.php
- Raw: https://pluginprobe.com/plugins/onwebchat/3.8.1/raw/admin/tabs/woocommerce.php
- Modified: 2026-07-08T12:31:52+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/onwebchat/3.8.1/code/admin/tabs/woocommerce.php#L10-L20`.

```php
<?php
/**
 * WooCommerce Tab - Product Sync Settings
 */

if (!defined('ABSPATH')) {
    exit;
}

function onwebchat_woocommerce_tab() {
    
    // Handle form submissions
    onwebchat_handle_woocommerce_actions();
    
    // Get current settings
    $sync_enabled = get_option('onwebchat_wc_sync_enabled', false);
    $sync_mode = get_option('onwebchat_wc_sync_mode', 'short_fallback_full');
    $secret = get_option('onwebchat_wc_sync_secret', '');
    $order_lookup_enabled = get_option('onwebchat_wc_order_lookup_enabled', false);
    
    // Get sync status
    $sync_status = array(
        'last_sync' => get_option('onwebchat_wc_last_bulk_sync', 0),
        'in_progress' => get_option('onwebchat_wc_bulk_in_progress', false),
        'done' => get_option('onwebchat_wc_bulk_done', 0),
        'total' => get_option('onwebchat_wc_bulk_total', 0),
        'last_sync_start' => get_option('onwebchat_wc_last_sync_start', 0),
    );
    
    // Calculate cooldown status
    $cooldown_period = 5 * 60; // 5 minutes // 5min // 5 * 60    //also in the file woocommerce-sync.php 
    $time_since_last_sync = time() - $sync_status['last_sync_start'];
    $is_in_cooldown = ($time_since_last_sync < $cooldown_period) && $sync_status['last_sync_start'] > 0;
    $cooldown_remaining = $is_in_cooldown ? ceil(($cooldown_period - $time_since_last_sync) / 60) : 0;
    
    ?>
    
    <?php if (isset($_GET['wc_saved']) && $_GET['wc_saved'] == '1'): ?>
        <div class="notice notice-success is-dismissible">
            <p><strong>WooCommerce settings saved successfully!</strong></p>
        </div>
    <?php endif; ?>
    
    <?php 
    // Check for authentication errors
    $auth_error = get_transient('onwebchat_wc_auth_error');
    if ($auth_error): 
    ?>
        <div class="notice notice-error is-dismissible">
            <p><strong>⚠️ WooCommerce Sync Authentication Error:</strong></p>
            <p><?php echo esc_html($auth_error); ?></p>
            <p>This usually happens when:</p>
            <ul style="list-style: disc; margin-left: 20px;">
                <li>You're trying to connect the plugin to a different onWebChat account</li>
            </ul>
            <p><strong>Solution:</strong> Please enter your onWebChat account credentials again in the "Connect WooCommerce Sync" section below and click "Connect WooCommerce Sync" button to reconnect.</p>
        </div>
    <?php endif; ?>
    
    <h2>WooCommerce Product Sync</h2>
    <p>
        Let your AI chatbot understand your WooCommerce products. 
        When enabled, products are automatically synced and kept up to date, allowing the AI to answer product-related questions accurately.
    </p>
    
    <?php if (empty($secret)): ?>
    <!-- Authentication required section -->
    <div class="notice notice-warning" style="margin: 15px 0; padding: 15px;">
        <h3 style="margin-top: 0;">🔐 Connect WooCommerce Sync</h3>
        <p>
            To enable WooCommerce sync, please enter your onWebChat account credentials below.
        </p>
        <p style="color: #666; font-size: 13px;">
            <!-- <strong>💡 Tip:</strong> If you originally connected using email/password in the <a href="?page=onwebchat_settings&tab=general">General tab</a>, 
            try unlinking and re-linking your account there. WooCommerce sync will be connected automatically! -->
        </p>
        
        <table class="form-table" style="margin-bottom: 0;">
            <tr>
                <th scope="row"><label for="onwebchat_wc_email">onWebChat Email (username)</label></th>
                <td>
                    <input type="email" 
                           id="onwebchat_wc_email" 
                           class="regular-text" 
                           placeholder="Your registered email"
                           value="<?php echo esc_attr(get_option('onwebchat_plugin_option_user', '')); ?>">
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="onwebchat_wc_password">onWebChat Password</label></th>
                <td>
                    <input type="password" 
                           id="onwebchat_wc_password" 
                           class="regular-text" 
                           placeholder="Your account password">
                </td>
            </tr>
        </table>
        
        <p style="margin-top: 15px;">
            <button type="button" id="onwebchat_wc_connect" class="button button-primary">
                Connect WooCommerce Sync
            </button>
            <span id="onwebchat_wc_connect_status" style="margin-left: 10px;"></span>
        </p>
    </div>
    
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#onwebchat_wc_connect').on('click', function() {
            var email = $('#onwebchat_wc_email').val();
            var password = $('#onwebchat_wc_password').val();
            
            if (!email || !password) {
                alert('Please enter both email and password.');
                return;
            }
            
            var $btn = $(this);
            var $status = $('#onwebchat_wc_connect_status');
            
            $btn.prop('disabled', true).text('Connecting...');
            $status.html('');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'onwebchat_wc_connect',
                    email: email,
                    password: password,
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        $status.html('<span style="color: green;">✓ Connected successfully!</span>');
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        // Render the server-supplied error as TEXT (never HTML) so a malicious/MITM'd
                        // API response can't inject markup into the admin page.
                        $status.empty().append(
                            $('<span/>').css('color', 'red').text('✗ ' + response.data)
                        );
                        $btn.prop('disabled', false).text('Connect WooCommerce Sync');
                    }
                },
                error: function() {
                    $status.html('<span style="color: red;">✗ Connection error. Please try again.</span>');
                    $btn.prop('disabled', false).text('Connect WooCommerce Sync');
                }
            });
        });
    });
    </script>
    
    <?php else: ?>
    <!-- Connected - show settings -->
    
    <form action="admin.php?page=onwebchat_settings&tab=woocommerce" method="post">
        <input type="hidden" name="action" value="save_wc_sync">
        <?php wp_nonce_field('onwebchat_wc_sync_nonce'); ?>
        
        <table class="form-table">
            <tr>
                <th scope="row" style="line-height: 1 !important;">
                    <label for="onwebchat_wc_sync_enabled">Enable Product Sync</label>
                </th>
                <td>
                    <label for="onwebchat_wc_sync_enabled">
                        <input type="checkbox" 
                               id="onwebchat_wc_sync_enabled" 
                               name="onwebchat_wc_sync_enabled" 
                               value="1" 
                               <?php checked($sync_enabled, true); ?>>
                        Automatically sync products to onWebChat for AI training
                    </label>
                    <p id="onwebchat_wc_sync_status" style="margin: 8px 0 0 0; font-size: 13px; min-height: 20px; visibility: hidden; opacity: 0;">
                    </p>
                </td>
            </tr>
            
            <tr style="display: none;">
                <th scope="row">
                    <label for="onwebchat_wc_sync_mode">Description Mode</label>
                </th>
                <td>
                    <select id="onwebchat_wc_sync_mode" name="onwebchat_wc_sync_mode" style="width: 350px;">
                        <option value="short_only" <?php selected($sync_mode, 'short_only'); ?>>
                            Short description only
                        </option>
                        <option value="short_fallback_full" <?php selected($sync_mode, 'short_fallback_full'); ?>>
                            Short description (fallback to full)
                        </option>
                    </select>
                    <p class="description">
                        Choose how product descriptions are synced for AI training
                    </p>
                </td>
            </tr>
            
            <?php if (!empty($secret)): ?>
            <tr>
                <th scope="row">Connection Status</th>
                <td>
                    <span style="color: green; font-weight: bold; vertical-align: middle;">✓ Connected to onWebChat</span>
                    <button type="button"
                            id="onwebchat_regenerate_secret"
                            class="button button-small"
                            style="margin-left: 10px; vertical-align: middle;">
                        Disconnect
                    </button>
                    <p class="description">
                        WooCommerce sync is securely connected. Click "Disconnect" to re-authenticate.
                    </p>
                </td>
            </tr>
            <?php endif; ?>
        </table>
    </form>

    <hr>

    <h2>AI Order Status Lookup</h2>
    <p>
        Let your AI chatbot answer "where is my order?" with live data. The store verifies identity using the
        order number and email (signed-in users only need the order number) before sharing details.
    </p>

    <table class="form-table">
        <tr>
            <th scope="row" style="line-height: 1 !important;">
                <label for="onwebchat_wc_order_lookup_enabled">Enable Order Status Lookup</label>
            </th>
            <td>
                <label for="onwebchat_wc_order_lookup_enabled">
                    <input type="checkbox"
                           id="onwebchat_wc_order_lookup_enabled"
                           name="onwebchat_wc_order_lookup_enabled"
                           value="1"
                           <?php checked($order_lookup_enabled, true); ?>>
                    Allow the AI chatbot to look up live order status (with identity verification)
                </label>
                <p id="onwebchat_wc_order_lookup_status" style="margin: 8px 0 0 0; font-size: 13px; min-height: 20px; visibility: hidden; opacity: 0;">
                </p>
            </td>
        </tr>
    </table>

    <script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#onwebchat_wc_order_lookup_enabled').on('change', function() {
            var $checkbox = $(this);
            var $status = $('#onwebchat_wc_order_lookup_status');
            var isEnabled = $checkbox.is(':checked');

            $checkbox.prop('disabled', true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'onwebchat_wc_save_order_lookup',
                    order_lookup_enabled: isEnabled ? '1' : '0',
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        var autohide = true;
                        if (response.data.warning) {
                            // Local testing mode: saved locally, but the onWebChat server was not notified.
                            $status.empty().append(
                                $('<span/>').css('color', '#996800').text('⚠ ' + (response.data.message || 'Saved locally; onWebChat server not notified.'))
                            );
                            autohide = false;
                        } else if (response.data.enabled) {
                            $status.html('<span style="color: green;">✅ AI order status lookup enabled</span>');
                        } else {
                            $status.html('<span style="color: #d63638;">❌ AI order status lookup disabled</span>');
                        }
                        $status.css('visibility', 'visible').css('opacity', 1);
                        if (autohide) {
                            setTimeout(function() {
                                $status.animate({opacity: 0}, 300, function() {
                                    $status.css('visibility', 'hidden');
                                });
                            }, 1700);
                        }
                    } else {
                        // Revert checkbox on error
                        $checkbox.prop('checked', !isEnabled);
                        alert('Error: ' + (response.data || 'Failed to save setting'));
                    }
                    $checkbox.prop('disabled', false);
                },
                error: function() {
                    $checkbox.prop('checked', !isEnabled);
                    alert('An error occurred. Please try again.');
                    $checkbox.prop('disabled', false);
                }
            });
        });
    });
    </script>

    <hr>

    <h2>Bulk Sync Status</h2>

    <?php
    // Large-catalogue category picker. Stores above the threshold can choose
    // which categories to sync (staying within the hard cap); the choice is
    // persisted as the ongoing auto-sync scope. Below the threshold the whole
    // catalogue is synced as before and no picker is shown.
    if (class_exists('OnWebChat_WooCommerce_Sync')) {
        $owc_threshold = OnWebChat_WooCommerce_Sync::CATEGORY_SELECT_THRESHOLD;
        $owc_max       = OnWebChat_WooCommerce_Sync::MAX_SYNC_PRODUCTS;
    } else {
        $owc_threshold = 2000;
        $owc_max       = 15000;
    }

    $owc_counts = wp_count_posts('product');
    $owc_published_count = (is_object($owc_counts) && isset($owc_counts->publish)) ? (int) $owc_counts->publish : 0;
    $owc_needs_selection = $owc_published_count > $owc_threshold;
    $owc_over_max        = $owc_published_count > $owc_max;

    // Saved sync scope (product_cat term IDs) to pre-tick in the picker.
    $owc_saved_scope = array();
    $owc_scope_raw = (string) get_option('onwebchat_wc_sync_categories', '');
    if ($owc_scope_raw !== '') {
        foreach (explode(',', $owc_scope_raw) as $owc_sid) {
            $owc_sid = (int) trim($owc_sid);
            if ($owc_sid > 0) {
                $owc_saved_scope[] = $owc_sid;
            }
        }
    }

    $owc_categories = $owc_needs_selection ? get_terms(array(
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
        'orderby'    => 'name',
        'order'      => 'ASC',
    )) : array();
    if (is_wp_error($owc_categories)) {
        $owc_categories = array();
    }

    // Build the category tree. The picker only offers top-level categories, and
    // selecting one covers its whole subtree, so each row shows a distinct product
    // count spanning the category and all of its descendants.
    $owc_children = array(); // parent_id => array of term objects
    foreach ($owc_categories as $owc_term) {
        $owc_children[(int) $owc_term->parent][] = $owc_term;
    }

    // Distinct published products in a category and its whole subtree. Counting
    // distinct posts (WP_Query found_posts with include_children) avoids the
    // over-count you get from summing per-term counts when a product is assigned
    // to both a parent and a child category.
    if (!function_exists('owc_subtree_product_count')) {
        function owc_subtree_product_count($term_id) {
            $query = new WP_Query(array(
                'post_type'      => 'product',
                'post_status'    => 'publish',
                'posts_per_page' => 1,
                'fields'         => 'ids',
                'no_found_rows'  => false,
                'tax_query'      => array(array(
                    'taxonomy'         => 'product_cat',
                    'field'            => 'term_id',
                    'terms'            => (int) $term_id,
                    'include_children' => true,
                )),
            ));
            return (int) $query->found_posts;
        }
    }

    // Renderable top-level categories (parent 0) that actually cover products.
    $owc_top_rows = array();
    $owc_top_level = isset($owc_children[0]) ? $owc_children[0] : array();
    foreach ($owc_top_level as $owc_term) {
        $owc_count = owc_subtree_product_count((int) $owc_term->term_id);
        if ($owc_count > 0) {
            $owc_top_rows[] = array('term' => $owc_term, 'count' => $owc_count);
        }
    }
    ?>

    <?php if ($owc_needs_selection && !empty($owc_top_rows)): ?>
    <div id="owc-category-picker" style="background: #f9f9f9; padding: 20px; border-radius: 8px; max-width: 800px; margin-top: 15px;">
        <p style="margin: 0 0 10px 0;"><strong>Choose what to sync</strong></p>
        <p id="owc-category-intro" style="margin: 0 0 12px 0; color: #555;">
            <?php if ($owc_over_max): ?>
                <?php printf(
                    'Your store has %s products. onWebChat can sync up to %s, so please tick the categories you want to sync. Selecting a category includes all of its subcategories.',
                    esc_html(number_format_i18n($owc_published_count)),
                    esc_html(number_format_i18n($owc_max))
                ); ?>
            <?php else: ?>
                <?php printf(
                    'Your store has %s products. Leave every category unticked to sync the whole catalogue, including products without a category, or tick specific categories to sync only those. Selecting a category includes all of its subcategories.',
                    esc_html(number_format_i18n($owc_published_count))
                ); ?>
            <?php endif; ?>
        </p>
        <p style="margin: 0 0 10px 0;">
            <input type="text" id="owc-category-search" placeholder="Search categories..." class="regular-text" style="max-width: 360px;">
        </p>
        <p style="margin: 0 0 8px 0;">
            <label><input type="checkbox" id="owc-category-all"> <strong>Select all</strong></label>
            <span id="owc-category-selected" style="margin-left: 12px; color: #666;"></span>
        </p>
        <div id="owc-category-list" style="max-height: 280px; overflow: auto; border: 1px solid #ddd; border-radius: 4px; background: #fff; padding: 8px 12px;">
            <?php foreach ($owc_top_rows as $owc_row): $owc_term = $owc_row['term']; ?>
                <label class="owc-category-row" data-name="<?php echo esc_attr(strtolower($owc_term->name)); ?>" style="display: block; padding: 3px 0;">
                    <input type="checkbox" class="owc-category-cb" value="<?php echo (int) $owc_term->term_id; ?>" <?php echo in_array((int) $owc_term->term_id, $owc_saved_scope, true) ? 'checked' : ''; ?>>
                    <?php echo esc_html($owc_term->name); ?>
                    <span style="color: #999;">(<?php echo (int) $owc_row['count']; ?>)</span>
                </label>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <div id="onwebchat_sync_status_display" style="background: #f9f9f9; padding: 20px; border-radius: 8px; max-width: 800px; margin-top: 15px;">
        <?php if ($sync_status['in_progress']): ?>
            <p style="margin: 0 0 10px 0;">
                <strong>⏳ Sync in progress:</strong> 
                <?php echo esc_html($sync_status['done']); ?> / <?php echo esc_html($sync_status['total']); ?> products synced
            </p>
            <div style="background: #fff; border: 1px solid #ddd; border-radius: 4px; height: 20px; overflow: hidden;">
                <div style="background: #2271b1; height: 100%; width: <?php echo $sync_status['total'] > 0 ? ($sync_status['done'] / $sync_status['total'] * 100) : 0; ?>%; transition: width 0.3s;"></div>
            </div>
        <?php elseif ($sync_status['last_sync'] > 0): ?>
            <p id="onwebchat_last_sync_info" style="margin: 0;">
                <strong>✓ Last bulk sync:</strong> 
                <?php echo esc_html(human_time_diff($sync_status['last_sync'], current_time('timestamp')) . ' ago'); ?>
            </p>
            <p id="onwebchat_total_synced_info" style="margin: 10px 0 0 0; color: #666;">
                Total products synced: <?php echo esc_html($sync_status['total']); ?>
            </p>
        <?php else: ?>
            <p style="margin: 0; color: #666;">
                No bulk sync has been performed yet.
            </p>
        <?php endif; ?>
        
        <?php if (!$is_in_cooldown): ?>
        <p style="margin-top: 15px;">
            <button type="button" 
                    id="onwebchat_sync_now" 
                    class="button button-primary" 
                    <?php echo $sync_status['in_progress'] ? 'disabled' : ''; ?>>
                <?php echo $sync_status['in_progress'] ? 'Sync in Progress...' : 'Sync All Products Now'; ?>
            </button>
        </p>
        <?php endif; ?>
        
        <p class="description onwebchat-sync-description" style="margin-top: 10px;">
            <?php if ($is_in_cooldown): ?>
                <?php if ($sync_enabled): ?>
                    Bulk sync was completed recently. Your products are already up to date, and any new or updated products will be synced automatically.
                <?php else: ?>
                    Bulk sync was completed recently. Your products are already up to date. Please enable "Automatically sync products to onWebChat for AI training" above to keep all your products synced automatically.
                <?php endif; ?>
            <?php else: ?>
                Click to sync all existing products. This process runs in the background and may take several minutes depending on your product count.
            <?php endif; ?>
        </p>
        
        <?php 
        // Show reset button if sync appears stuck (done >= total OR in progress for more than 3 minutes)
        $stuck_sync = $sync_status['in_progress'] && (
            $sync_status['done'] >= $sync_status['total'] || 
            (time() - $sync_status['last_sync_start'] > 180)
        );
        if ($stuck_sync): 
        ?>
            <p style="margin-top: 10px;">
                <button type="button" 
                        id="onwebchat_manual_process_batch" 
                        class="button button-secondary"
                        style="margin-right: 10px;">
                    Process Batch Manually
                </button>
                <button type="button" 
                        id="onwebchat_reset_sync_status" 
                        class="button">
                    Mark Sync as Complete
                </button>
                <span class="description" style="margin-left: 10px;">
                    If sync appears stuck, try processing manually or reset status.
                </span>
            </p>
        <?php endif; ?>
    </div>
    
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // Cooldown timer - reload page when cooldown expires
        <?php if ($is_in_cooldown): ?>
        var cooldownSeconds = <?php echo ($cooldown_period - $time_since_last_sync); ?>;
        setTimeout(function() {
            location.reload();
        }, cooldownSeconds * 1000);
        <?php endif; ?>

        // ---- Large-catalogue category picker ----
        var owcOverMax = <?php echo (!empty($owc_over_max)) ? 'true' : 'false'; ?>;
        var owcHasPicker = $('#owc-category-picker').length > 0;

        function owcSelectedCategoryIds() {
            var ids = [];
            $('.owc-category-cb:checked').each(function() {
                ids.push($(this).val());
            });
            return ids;
        }

        function owcUpdateSyncButtonLabel() {
            var $btn = $('#onwebchat_sync_now');
            if (!$btn.length || $btn.prop('disabled')) {
                return;
            }
            var label = (owcOverMax || owcSelectedCategoryIds().length > 0)
                ? 'Sync selected categories'
                : 'Sync All Products Now';
            $btn.text(label);
        }

        function owcUpdateSelected() {
            var selected = owcSelectedCategoryIds().length;
            var total = $('.owc-category-cb').length;
            $('#owc-category-selected').text(selected > 0 ? (selected + ' of ' + total + ' categories selected') : '');
            $('#owc-category-all').prop('checked', total > 0 && selected === total);
            owcUpdateSyncButtonLabel();
        }

        if (owcHasPicker) {
            $('.owc-category-cb').on('change', owcUpdateSelected);

            // Select all toggles only the rows currently visible (respects search).
            $('#owc-category-all').on('change', function() {
                var checked = $(this).is(':checked');
                $('.owc-category-row:visible').find('.owc-category-cb').prop('checked', checked);
                owcUpdateSelected();
            });

            $('#owc-category-search').on('input', function() {
                var q = $(this).val().toLowerCase();
                $('.owc-category-row').each(function() {
                    var name = String($(this).data('name'));
                    $(this).toggle(name.indexOf(q) !== -1);
                });
            });

            // Reflect the saved scope (pre-ticked categories) and set the label.
            owcUpdateSelected();
        }

        // Sync enabled checkbox - save immediately via AJAX
        $('#onwebchat_wc_sync_enabled').on('change', function() {
            var $checkbox = $(this);
            var $status = $('#onwebchat_wc_sync_status');
            var $syncDescription = $('.onwebchat-sync-description');
            var isEnabled = $checkbox.is(':checked');
            
            // Disable checkbox while saving
            $checkbox.prop('disabled', true);
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'onwebchat_wc_save_sync_enabled',
                    sync_enabled: isEnabled ? '1' : '0',
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        if (response.data.enabled) {
                            $status.html('<span style="color: green;">✅ WooCommerce product sync enabled</span>');
                            // Update the sync description text if in cooldown
                            if ($syncDescription.length) {
                                var currentText = $syncDescription.text().trim();
                                if (currentText.includes('Bulk sync was completed recently')) {
                                    $syncDescription.text('Bulk sync was completed recently. Your products are already up to date, and any new or updated products will be synced automatically.');
                                }
                            }
                        } else {
                            $status.html('<span style="color: #d63638;">❌ WooCommerce product sync disabled</span>');
                            // Update the sync description text if in cooldown
                            if ($syncDescription.length) {
                                var currentText = $syncDescription.text().trim();
                                if (currentText.includes('Bulk sync was completed recently')) {
                                    $syncDescription.text('Bulk sync was completed recently. Your products are already up to date. Please enable "Automatically sync products to onWebChat for AI training" above to keep all your products synced automatically.');
                                }
                            }
                        }
                        // Ensure status is visible and fade in smoothly
                        $status.css('visibility', 'visible').css('opacity', 1);
                        // Hide it after 2.5 seconds with fade out
                        setTimeout(function() {
                            $status.animate({opacity: 0}, 300, function() {
                                $status.css('visibility', 'hidden');
                            });
                        }, 1700);
                    } else {
                        // Revert checkbox on error
                        $checkbox.prop('checked', !isEnabled);
                        alert('Error: ' + (response.data || 'Failed to save setting'));
                    }
                    $checkbox.prop('disabled', false);
                },
                error: function() {
                    // Revert checkbox on error
                    $checkbox.prop('checked', !isEnabled);
                    alert('An error occurred. Please try again.');
                    $checkbox.prop('disabled', false);
                }
            });
        });
        
        // Sync now button
        $('#onwebchat_sync_now').on('click', function() {
            if ($(this).prop('disabled')) {
                return;
            }

            // Determine the sync scope from the category picker (if shown).
            var owcSelected = owcHasPicker ? owcSelectedCategoryIds() : [];

            // Above the hard cap a category selection is required.
            if (owcHasPicker && owcOverMax && owcSelected.length === 0) {
                alert('Your store has too many products to sync all at once. Please tick at least one category to sync.');
                return;
            }

            var confirmMsg = (owcSelected.length > 0)
                ? 'Sync products in the selected categories with onWebChat to train your AI chatbot?'
                : 'Sync all published products with onWebChat to train your AI chatbot?';
            if (!confirm(confirmMsg)) {
                return;
            }

            var $btn = $(this);
            $btn.prop('disabled', true).text('Syncing products...');
            
            // Hide the "Last sync" info while syncing
            $('#onwebchat_last_sync_info').hide();
            $('#onwebchat_total_synced_info').hide();
            
            // Show initial syncing message with progress bar
            $('#onwebchat_sync_status_display').html(
                '<p style="margin: 0 0 10px 0;"><strong>⏳ Sync in progress:</strong> <span id="sync_progress_text">0 / ? products synced</span></p>' +
                '<div style="background: #fff; border: 1px solid #ddd; border-radius: 4px; height: 20px; overflow: hidden;">' +
                    '<div id="sync_progress_bar" style="background: #2271b1; height: 100%; width: 0%; transition: width 0.3s;"></div>' +
                '</div>' +
                '<p style="margin: 10px 0 0 0; color: #666;">Please wait, this may take several minutes.</p>'
            );
            
            // Start polling for progress updates
            var progressInterval = setInterval(function() {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'onwebchat_wc_get_sync_status',
                        nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                    },
                    success: function(statusResponse) {
                        if (statusResponse.success && statusResponse.data.in_progress) {
                            var done = statusResponse.data.done || 0;
                            var total = statusResponse.data.total || 0;
                            var percentage = total > 0 ? Math.round((done / total) * 100) : 0;
                            
                            $('#sync_progress_text').text(done + ' / ' + total + ' products synced');
                            $('#sync_progress_bar').css('width', percentage + '%');
                        }
                    }
                });
            }, 2000); // Poll every 2 seconds
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                timeout: 120000, // 2 minute timeout for large syncs
                data: {
                    action: 'onwebchat_wc_sync_now',
                    categories: owcSelected.join(','),
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    clearInterval(progressInterval); // Stop polling
                    
                    if (response.success) {
                        var result = response.data.result;
                        var stats = result.stats;
                        var msg = 'Sync completed!\n\n' +
                            'Products processed: ' + result.done + '/' + response.data.total + '\n' +
                            'Created: ' + stats.created + '\n' +
                            'Updated: ' + stats.updated + '\n' +
                            'Unchanged: ' + stats.skipped + '\n' +
                            'Errors: ' + stats.errors;
                        alert(msg);
                        location.reload();
                    } else {
                        alert('Error: ' + response.data);
                        $btn.prop('disabled', false);
                        owcUpdateSyncButtonLabel();
                    }
                },
                error: function(xhr, status, error) {
                    clearInterval(progressInterval); // Stop polling
                    alert('An error occurred: ' + error + '. Please try again.');
                    $btn.prop('disabled', false);
                    owcUpdateSyncButtonLabel();
                }
            });
        });
        
        // Manual process batch button (for debugging stuck syncs)
        $('#onwebchat_manual_process_batch').on('click', function() {
            var $btn = $(this);
            $btn.prop('disabled', true).text('Processing...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'onwebchat_wc_manual_process_batch',
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        alert('Batch processed. Check console/logs for details.');
                        location.reload();
                    } else {
                        alert('Error: ' + response.data);
                        $btn.prop('disabled', false).text('Process Batch Manually');
                    }
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $btn.prop('disabled', false).text('Process Batch Manually');
                }
            });
        });
        
        // Reset sync status button
        $('#onwebchat_reset_sync_status').on('click', function() {
            if (!confirm('Mark sync as complete? This will reset the progress indicator.')) {
                return;
            }
            
            var $btn = $(this);
            $btn.prop('disabled', true).text('Resetting...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'onwebchat_wc_reset_sync_status',
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + response.data);
                        $btn.prop('disabled', false).text('Mark Sync as Complete');
                    }
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $btn.prop('disabled', false).text('Mark Sync as Complete');
                }
            });
        });
        
        // Regenerate secret button (now "Disconnect" button)
        $('#onwebchat_regenerate_secret').on('click', function() {
            if (!confirm('This will disconnect WooCommerce sync. You will need to re-authenticate with your credentials. Continue?')) {
                return;
            }
            
            var $btn = $(this);
            $btn.prop('disabled', true).text('Disconnecting...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'onwebchat_wc_regenerate_secret',
                    nonce: '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        alert('WooCommerce sync disconnected. Please re-authenticate to continue syncing.');
                        location.reload();
                    } else {
                        alert('Error: ' + response.data);
                        $btn.prop('disabled', false).text('Disconnect');
                    }
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $btn.prop('disabled', false).text('Disconnect');
                }
            });
        });
    });
    </script>
    
    <?php endif; // End if secret exists ?>
    
    <?php
}

/**
 * Handle form submissions for WooCommerce tab
 */
function onwebchat_handle_woocommerce_actions() {
    
    if (isset($_POST["action"]) && $_POST["action"] == "save_wc_sync") {
        
        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'onwebchat_wc_sync_nonce')) {
            wp_die('Sorry, your nonce did not verify.');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions.');
        }
        
        // Save settings
        $sync_enabled = isset($_POST["onwebchat_wc_sync_enabled"]) ? true : false;
        $sync_mode = isset($_POST["onwebchat_wc_sync_mode"]) ? sanitize_text_field($_POST["onwebchat_wc_sync_mode"]) : 'short_fallback_full';
        
        update_option('onwebchat_wc_sync_enabled', $sync_enabled);
        update_option('onwebchat_wc_sync_mode', $sync_mode);
        
        // Secret is now obtained via authenticated connection, not auto-generated
        
        wp_redirect(admin_url('admin.php?page=onwebchat_settings&tab=woocommerce&wc_saved=1'));
        exit;
    }
}


```
