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

AI Chatbot for WooCommerce &amp; Live Chat – onWebChat, version 3.10.0. 1,287 lines.

- Page: https://pluginprobe.com/plugins/onwebchat/3.10.0/code/admin/tabs/woocommerce.php
- Raw: https://pluginprobe.com/plugins/onwebchat/3.10.0/raw/admin/tabs/woocommerce.php
- Modified: 2026-09-16T06:54:04+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.10.0/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_plus_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),
    );
    
    // What the AI training data currently covers (point 4 of the scope model):
    // the saved scope IS what was synced, because a sync only ever adds to it.
    global $onwebchat_wc_sync;
    $owc_scope_summary = (isset($onwebchat_wc_sync) && is_object($onwebchat_wc_sync) && method_exists($onwebchat_wc_sync, 'get_scope_summary'))
        ? $onwebchat_wc_sync->get_scope_summary()
        : null;

    // Calculate cooldown status
    // Short on purpose: it only guards against double-clicking the sync button.
    // Now that the selection is cumulative, syncing again straight after a run is
    // a normal thing to do (you just ticked another subcategory), so a long block
    // gets in the way. The button stays VISIBLE and disabled with a live
    // countdown, instead of disappearing as it used to.
    // Also in includes/woocommerce-sync.php.
    $cooldown_period = 30; // seconds
    $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 ? max(1, $cooldown_period - $time_since_last_sync) : 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>Product Sync for the AI Chatbot</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>
                <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_plus_full" <?php selected($sync_mode, 'short_plus_full'); ?>>
                            Short + full description (default)
                        </option>
                        <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.
                        The default sends both texts, so the AI bot also learns the
                        detailed description (intended use, compatibility, specs).
                    </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 whole category tree for the picker. Every category is offered
    // (subcategories indented under their parent, searchable by name or path),
    // and selecting one covers its whole subtree, so each row shows a distinct
    // product count spanning the category and all of its descendants.
    $owc_term_by_id = array(); // term_id => term object
    foreach ($owc_categories as $owc_term) {
        $owc_term_by_id[(int) $owc_term->term_id] = $owc_term;
    }

    $owc_children  = array(); // parent_id => array of term objects (name order, from get_terms)
    $owc_parent_of = array(); // term_id => parent term_id (0 for roots and orphans)
    foreach ($owc_categories as $owc_term) {
        $owc_pid = (int) $owc_term->parent;
        if (!isset($owc_term_by_id[$owc_pid])) {
            $owc_pid = 0; // orphan (parent missing): treat as a root
        }
        $owc_parent_of[(int) $owc_term->term_id] = $owc_pid;
        $owc_children[$owc_pid][] = $owc_term;
    }

    // Distinct published products per category subtree, computed in ONE pass:
    // read every (product, category) pair of the published products and, for
    // each product, credit the category and each of its ancestors once. Counting
    // per product avoids the over-count you get from summing per-term counts when
    // a product sits in both a parent and a child category, and one query keeps
    // the page fast even with more than a thousand categories (a WP_Query per
    // category would not).
    $owc_counts = array(); // term_id => distinct published products in the subtree
    if (!empty($owc_categories)) {
        global $wpdb;
        $owc_pairs = $wpdb->get_results($wpdb->prepare(
            "SELECT tr.object_id, tt.term_id
             FROM {$wpdb->term_relationships} tr
             INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
             INNER JOIN {$wpdb->posts} p ON p.ID = tr.object_id
             WHERE tt.taxonomy = %s AND p.post_type = %s AND p.post_status = %s
             ORDER BY tr.object_id",
            'product_cat', 'product', 'publish'
        ), ARRAY_N);
        if (!is_array($owc_pairs)) {
            $owc_pairs = array();
        }

        $owc_current_product = 0;
        $owc_credited = array(); // categories already credited for the current product
        foreach ($owc_pairs as $owc_pair) {
            $owc_product_id = (int) $owc_pair[0];
            if ($owc_product_id !== $owc_current_product) {
                $owc_current_product = $owc_product_id;
                $owc_credited = array();
            }
            // Walk up to the root; stop at a category already credited for this
            // product (its ancestors were credited on that walk too).
            $owc_walk = (int) $owc_pair[1];
            $owc_hops = 0;
            while ($owc_walk > 0 && isset($owc_parent_of[$owc_walk]) && !isset($owc_credited[$owc_walk]) && $owc_hops++ < 100) {
                $owc_credited[$owc_walk] = true;
                $owc_counts[$owc_walk] = isset($owc_counts[$owc_walk]) ? $owc_counts[$owc_walk] + 1 : 1;
                $owc_walk = $owc_parent_of[$owc_walk];
            }
        }
        unset($owc_pairs, $owc_credited);
    }

    // Rows in tree order (depth first, siblings by name), skipping categories
    // whose subtree holds no published product. Anything not reached from the
    // roots (e.g. a parent loop) is appended as a root so nothing is hidden.
    $owc_rows = array(); // each: term, name, count, level, parents (path prefix)
    $owc_visited = array();
    for ($owc_pass = 0; $owc_pass < 2; $owc_pass++) {
        if ($owc_pass === 0) {
            $owc_roots = isset($owc_children[0]) ? $owc_children[0] : array();
        } else {
            $owc_roots = array();
            foreach ($owc_categories as $owc_term) {
                if (!isset($owc_visited[(int) $owc_term->term_id])) {
                    $owc_roots[] = $owc_term;
                }
            }
        }
        $owc_stack = array();
        foreach (array_reverse($owc_roots) as $owc_term) {
            $owc_stack[] = array($owc_term, 0, '');
        }
        while (!empty($owc_stack)) {
            list($owc_term, $owc_level, $owc_parents) = array_pop($owc_stack);
            $owc_id = (int) $owc_term->term_id;
            if (isset($owc_visited[$owc_id])) {
                continue;
            }
            $owc_visited[$owc_id] = true;
            $owc_count = isset($owc_counts[$owc_id]) ? $owc_counts[$owc_id] : 0;
            if ($owc_count === 0) {
                continue; // empty subtree (descendants are counted into their ancestors)
            }
            $owc_name = html_entity_decode((string) $owc_term->name, ENT_QUOTES, 'UTF-8');
            $owc_rows[] = array(
                'term'    => $owc_term,
                'name'    => $owc_name,
                'count'   => $owc_count,
                'level'   => $owc_level,
                'parents' => $owc_parents,
            );
            if (!empty($owc_children[$owc_id])) {
                foreach (array_reverse($owc_children[$owc_id]) as $owc_child) {
                    $owc_stack[] = array($owc_child, $owc_level + 1, $owc_parents . $owc_name . ' > ');
                }
            }
        }
    }
    unset($owc_visited, $owc_stack, $owc_term_by_id, $owc_children);
    ?>

    <?php if ($owc_needs_selection && !empty($owc_rows)): ?>
    <style>
        #owc-category-list .owc-category-row { display: block; padding-top: 3px; padding-bottom: 3px; }
        #owc-category-list .owc-cat-path { display: none; color: #999; }
        #owc-category-list.owc-filtering .owc-cat-path { display: inline; }
        #owc-category-list .owc-category-implied { color: #8c8f94; }
    </style>
    <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. Type in the search box to find any category or subcategory.',
                    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. Type in the search box to find any category or subcategory.',
                    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 and subcategories..." 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_rows as $owc_row): $owc_term = $owc_row['term']; $owc_indent = (int) $owc_row['level'] * 18; ?>
                <label class="owc-category-row" data-path="<?php echo esc_attr($owc_row['parents'] . $owc_row['name']); ?>" data-parent="<?php echo (int) $owc_parent_of[(int) $owc_term->term_id]; ?>" data-indent="<?php echo $owc_indent; ?>" style="padding-left: <?php echo $owc_indent; ?>px;">
                    <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 if ($owc_row['parents'] !== ''): ?><span class="owc-cat-path"><?php echo esc_html($owc_row['parents']); ?></span><?php endif; ?><?php echo esc_html($owc_row['name']); ?>
                    <span style="color: #999;">(<?php echo (int) $owc_row['count']; ?>)</span>
                </label>
            <?php endforeach; ?>
        </div>
        <p id="owc-scope-actions" style="margin: 12px 0 0 0;">
            <span id="owc-scope-removed-note" style="display: none; color: #b32d2e; margin-right: 10px;"></span>
            <button type="button" class="button button-secondary" id="owc-scope-remove" style="display: none;">
                Remove unticked categories from the AI training data
            </button>
            <span id="owc-scope-remove-progress" style="display: none; margin-left: 10px; color: #666;"></span>
        </p>
    </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 ($owc_scope_summary && !empty($owc_scope_summary['known'])): ?>
            <p id="onwebchat_scope_summary" style="margin: 10px 0 0 0; color: #666;">
                <strong>In your AI training data:</strong>
                <?php if ($owc_scope_summary['whole_catalogue']): ?>
                    <?php printf(
                        'your whole catalogue (%s products)',
                        esc_html(number_format_i18n($owc_scope_summary['products']))
                    ); ?>
                <?php elseif (!empty($owc_scope_summary['nothing'])): ?>
                    no products yet
                <?php else: ?>
                    <?php printf(
                        '%s %s, %s products',
                        esc_html(number_format_i18n($owc_scope_summary['categories'])),
                        esc_html($owc_scope_summary['categories'] === 1 ? 'category' : 'categories'),
                        esc_html(number_format_i18n($owc_scope_summary['products']))
                    ); ?>
                <?php endif; ?>
            </p>
        <?php endif; ?>
        
        <p style="margin-top: 15px;">
            <button type="button" 
                    id="onwebchat_sync_now" 
                    class="button button-primary" 
                    data-cooldown="<?php echo (int) $cooldown_remaining; ?>"
                    <?php echo ($sync_status['in_progress'] || $is_in_cooldown) ? 'disabled' : ''; ?>>
                <?php
                if ($sync_status['in_progress']) {
                    echo 'Sync in Progress...';
                } elseif ($is_in_cooldown) {
                    printf('Just synced, wait %ds', (int) $cooldown_remaining);
                } else {
                    echo 'Sync All Products Now';
                }
                ?>
            </button>
        </p>
        
        <p class="description onwebchat-sync-description" style="margin-top: 10px;">
            <?php if ($is_in_cooldown): ?>
                <?php if ($sync_enabled): ?>
                    A sync has just finished. The button is available again in a moment, so you can sync another selection right away.
                <?php else: ?>
                    A sync has just finished. Please enable "Automatically sync products to onWebChat for AI training" above to keep 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: count down on the button itself and enable it when it runs
        // out. The button used to be removed from the page entirely and only came
        // back on a reload, which read as "the sync button is gone".
        var $syncBtnCooldown = $('#onwebchat_sync_now');
        var owcCooldownLeft = parseInt($syncBtnCooldown.attr('data-cooldown'), 10) || 0;
        if (owcCooldownLeft > 0) {
            var owcCooldownTimer = setInterval(function() {
                owcCooldownLeft--;
                if (owcCooldownLeft > 0) {
                    $syncBtnCooldown.text('Just synced, wait ' + owcCooldownLeft + 's');
                    return;
                }
                clearInterval(owcCooldownTimer);
                $syncBtnCooldown.prop('disabled', false);
                $('.onwebchat-sync-description').text('Click to sync all existing products. This process runs in the background and may take several minutes depending on your product count.');
                // Restores "Sync All Products Now" / "Sync N new categories".
                if (typeof owcUpdateSyncButtonLabel === 'function') {
                    owcUpdateSyncButtonLabel();
                } else {
                    $syncBtnCooldown.text('Sync All Products Now');
                }
            }, 1000);
        }

        // ---- Large-catalogue category picker ----
        var owcOverMax = <?php echo (!empty($owc_over_max)) ? 'true' : 'false'; ?>;
        var owcHasPicker = $('#owc-category-picker').length > 0;
        // The categories already in the AI training data. A sync only ever ADDS to
        // this, so it is also the list a removal is measured against.
        var owcSavedScope = <?php echo wp_json_encode(array_map('strval', $owc_saved_scope)); ?>;
        // Nothing in the training data yet: every ticked category is a first sync,
        // so the button should not talk about what is "new" or a "re-sync".
        var owcScopeNone = <?php echo (!empty($owc_scope_summary['nothing'])) ? 'true' : 'false'; ?>;
        var owcCatParent = {};   // category id => parent id ('0' for top-level categories)
        var owcCatExplicit = {}; // category id => true when ticked by the merchant
        var owcFiltering = false;

        // Lower-case and strip accents, so "camasi" also finds a category with diacritics.
        function owcFold(str) {
            str = String(str || '').toLowerCase();
            if (str.normalize) {
                str = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
            }
            return str;
        }

        // Only explicit ticks are sent: a ticked category already covers its subtree.
        function owcSelectedCategoryIds() {
            var ids = [];
            $('.owc-category-cb').each(function() {
                if (owcCatExplicit[String(this.value)]) {
                    ids.push(String(this.value));
                }
            });
            return ids;
        }

        function owcHasTickedAncestor(id) {
            var parent = owcCatParent[id], hops = 0;
            while (parent && parent !== '0' && hops++ < 100) {
                if (owcCatExplicit[parent]) {
                    return true;
                }
                parent = owcCatParent[parent];
            }
            return false;
        }

        // Descendants of a ticked category show as ticked and disabled (implied)
        // and are handed back when the parent is unticked.
        function owcApplyTicks() {
            $('.owc-category-cb').each(function() {
                var id = String(this.value);
                var implied = owcHasTickedAncestor(id);
                this.disabled = implied;
                this.checked = implied || !!owcCatExplicit[id];
                $(this).closest('.owc-category-row').toggleClass('owc-category-implied', implied);
            });
        }

        // Is this category already in the training data, i.e. covered by the saved
        // scope itself or by one of its ancestors? Mirrors scope_covers() in PHP.
        function owcCoveredBy(list, id) {
            id = String(id);
            if (list.indexOf(id) !== -1) {
                return true;
            }
            var parent = owcCatParent[id], hops = 0;
            while (parent && parent !== '0' && hops++ < 100) {
                if (list.indexOf(parent) !== -1) {
                    return true;
                }
                parent = owcCatParent[parent];
            }
            return false;
        }

        // Ticked categories that are not in the training data yet: the only ones a
        // sync has to push.
        function owcAddedCategories() {
            if (!owcSavedScope.length) {
                return []; // whole catalogue already covered
            }
            return owcSelectedCategoryIds().filter(function(id) {
                return !owcCoveredBy(owcSavedScope, id);
            });
        }

        // Synced categories the merchant just unticked. Nothing happens to them
        // until the removal button below is used.
        function owcRemovedCategories() {
            var selected = owcSelectedCategoryIds();
            return owcSavedScope.filter(function(id) {
                return !owcCoveredBy(selected, id);
            });
        }

        function owcUpdateSyncButtonLabel() {
            var $btn = $('#onwebchat_sync_now');
            if (!$btn.length || $btn.prop('disabled')) {
                return;
            }
            var selected = owcSelectedCategoryIds().length;
            var added = owcAddedCategories().length;
            var label;
            if (!selected && !owcOverMax) {
                label = 'Sync All Products Now';
            } else if (owcScopeNone) {
                label = 'Sync selected ' + (selected === 1 ? 'category' : 'categories');
            } else if (added > 0) {
                label = 'Sync ' + added + (added === 1 ? ' new category' : ' new categories');
            } else {
                label = 'Re-sync selected categories';
            }
            $btn.text(label);
        }

        // Show the removal offer only while synced categories are unticked.
        function owcUpdateRemoveControls() {
            var $btn = $('#owc-scope-remove');
            if (!$btn.length) {
                return;
            }
            var removed = owcRemovedCategories().length;
            var $note = $('#owc-scope-removed-note');
            if (removed > 0) {
                $note.text('Unticked categories keep their products in your AI training data until you remove them.').show();
                $btn.text('Remove unticked categories from the AI training data (' + removed + ')').show();
            } else {
                $note.hide();
                $btn.hide();
            }
        }

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

        if (owcHasPicker) {
            $('.owc-category-row').each(function() {
                var $row = $(this);
                var cb = $row.find('.owc-category-cb')[0];
                if (!cb) {
                    return;
                }
                var id = String(cb.value);
                owcCatParent[id] = String($row.attr('data-parent') || '0');
                if (cb.checked) {
                    owcCatExplicit[id] = true; // saved sync scope
                }
                $row.data('fold', owcFold($row.attr('data-path')));
            });

            $('.owc-category-cb').on('change', function() {
                if (this.checked) {
                    owcCatExplicit[String(this.value)] = true;
                } else {
                    delete owcCatExplicit[String(this.value)];
                }
                owcApplyTicks();
                owcUpdateSelected();
            });

            // Select all: without a search it ticks every top-level category (the
            // whole tree); while searching it toggles only the rows currently shown.
            $('#owc-category-all').on('change', function() {
                var checked = this.checked;
                if (owcFiltering) {
                    $('.owc-category-row:visible .owc-category-cb').each(function() {
                        if (checked) {
                            owcCatExplicit[String(this.value)] = true;
                        } else {
                            delete owcCatExplicit[String(this.value)];
                        }
                    });
                } else {
                    owcCatExplicit = {};
                    if (checked) {
                        $.each(owcCatParent, function(id, parent) {
                            if (parent === '0') {
                                owcCatExplicit[id] = true;
                            }
                        });
                    }
                }
                owcApplyTicks();
                owcUpdateSelected();
            });

            // Search the whole tree by name or path ("shoes" also lists "Men > Shoes").
            // Matches are shown flat with their full path while a search is active.
            $('#owc-category-search').on('input', function() {
                var q = owcFold($(this).val().trim());
                owcFiltering = q !== '';
                $('#owc-category-list').toggleClass('owc-filtering', owcFiltering);
                $('.owc-category-row').each(function() {
                    var $row = $(this);
                    var hit = !owcFiltering || String($row.data('fold')).indexOf(q) !== -1;
                    $row.toggle(hit);
                    $row.css('padding-left', owcFiltering ? '0' : (parseInt($row.attr('data-indent'), 10) || 0) + 'px');
                });
            });

            // Reflect the saved scope (pre-ticked categories) and set the label.
            owcApplyTicks();
            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);
            var nonce = '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>';
            $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">Starting…</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 keep this page open until the sync completes.</p>'
            );

            function owcSyncFail(msg) {
                alert('Error: ' + msg);
                $btn.prop('disabled', false);
                owcUpdateSyncButtonLabel();
                $('#onwebchat_sync_status_display').html('');
            }

            function owcSyncProgress(done, total) {
                var pct = total > 0 ? Math.min(100, Math.round((done / total) * 100)) : 0;
                $('#sync_progress_text').text(done + ' / ' + total + ' products synced');
                $('#sync_progress_bar').css('width', pct + '%');
            }

            // Drive the sync one page per request until the run reports complete.
            // A single long request would outrun the server timeout on large
            // catalogues and report a false failure; this keeps every request
            // short and only reports success once the whole run is done.
            function owcRunBatch(total, attempt) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    // MUST stay above the 180s the PHP side allows for its own
                    // /product/batch call (see send_product_batch): on a first
                    // sync of long descriptions onWebChat summarizes every
                    // oversized product with a model call, so a page can take
                    // minutes. A browser timeout shorter than that aborts a
                    // request that is still running server-side, and the retry
                    // below then re-enters sync_next_page() concurrently, which
                    // double-counts the progress counters and can end the run
                    // early with products left unsynced.
                    timeout: 240000,
                    data: { action: 'onwebchat_wc_sync_batch', nonce: nonce },
                    success: function(resp) {
                        if (!resp || !resp.success) { owcSyncFail((resp && resp.data) || 'Sync failed'); return; }
                        var d = resp.data || {};
                        total = d.total || total;
                        owcSyncProgress(d.done || 0, total);

                        if (d.in_progress) {
                            owcRunBatch(total, 0);
                        } else {
                            var s = d.stats || {};
                            alert('Sync completed!\n\n' +
                                'Created: ' + (s.created || 0) + '\n' +
                                'Updated: ' + (s.updated || 0) + '\n' +
                                'Unchanged: ' + (s.skipped || 0) + '\n' +
                                'Errors: ' + (s.errors || 0));
                            location.reload();
                        }
                    },
                    error: function() {
                        // One page timing out is recoverable (progress is saved
                        // server-side): retry a few times before giving up.
                        if (attempt < 3) {
                            setTimeout(function() { owcRunBatch(total, attempt + 1); }, 3000);
                        } else {
                            owcSyncFail('A network error occurred. Some products may not have synced; please try again.');
                        }
                    }
                });
            }

            // Kick off the run, then let the browser drive the batches.
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                // Also processes the first page inline, so it needs the same
                // headroom as owcRunBatch above.
                timeout: 240000,
                data: {
                    action: 'onwebchat_wc_sync_start',
                    categories: owcSelected.join(','),
                    nonce: nonce
                },
                success: function(response) {
                    if (!response || !response.success) { owcSyncFail((response && response.data) || 'Could not start sync'); return; }
                    var total = response.data.total || 0;
                    owcSyncProgress(0, total);
                    // Starting a sync switches automatic sync on server-side; show it.
                    if (response.data.auto_sync_enabled) {
                        $('#onwebchat_wc_sync_enabled').prop('checked', true);
                    }
                    if (total === 0) {
                        alert('No products found to sync.');
                        $btn.prop('disabled', false);
                        owcUpdateSyncButtonLabel();
                        $('#onwebchat_sync_status_display').html('');
                        return;
                    }
                    owcRunBatch(total, 0);
                },
                error: function() {
                    owcSyncFail('Could not start sync. Please try again.');
                }
            });
        });

        // Explicit removal of unticked categories (point 3 of the scope model).
        // Unticking a category never deletes anything on its own; this button is
        // the only way products leave the AI training data from here, and it says
        // exactly how many are affected before doing it.
        $('#owc-scope-remove').on('click', function() {
            var $btn = $(this);
            var $progress = $('#owc-scope-remove-progress');
            var nonce = '<?php echo wp_create_nonce('onwebchat_wc_sync_nonce'); ?>';
            var keep = owcSelectedCategoryIds().join(',');

            $btn.prop('disabled', true);
            $progress.text('Checking...').show();

            function removeFail(message) {
                $btn.prop('disabled', false);
                $progress.hide().text('');
                alert(message);
            }

            function removeNextPage(total, done) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    timeout: 240000,
                    data: { action: 'onwebchat_wc_scope_remove_batch', nonce: nonce },
                    success: function(resp) {
                        if (!resp || !resp.success) { removeFail((resp && resp.data) || 'Could not remove the products.'); return; }
                        var d = resp.data || {};
                        done = d.done || done;
                        total = d.total || total;
                        $progress.text('Removed ' + done + ' / ' + total + '...');
                        if (d.complete) {
                            $progress.text('Done. Reloading...');
                            location.reload();
                            return;
                        }
                        removeNextPage(total, done);
                    },
                    error: function() {
                        removeFail('A network error occurred while removing the products. Some may still be in your AI training data; please try again.');
                    }
                });
            }

            // Ask the server how much this affects, confirm, then run.
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                timeout: 240000,
                data: { action: 'onwebchat_wc_scope_remove_start', categories: keep, nonce: nonce },
                success: function(resp) {
                    if (!resp || !resp.success) { removeFail((resp && resp.data) || 'Could not start the removal.'); return; }
                    var d = resp.data || {};
                    var total = d.total || 0;
                    var message = 'Remove ' + total + (total === 1 ? ' product' : ' products') +
                                  ' of ' + d.categories + (d.categories === 1 ? ' category' : ' categories') +
                                  ' from your AI training data?\n\nYour chatbot will stop answering questions about them.' +
                                  ' You can sync them again at any time.';
                    if (d.disables_sync) {
                        message += '\n\nNothing is left ticked, so automatic product sync will also be switched off.';
                    }

                    if (total === 0 || d.complete) {
                        location.reload();
                        return;
                    }

                    if (!window.confirm(message)) {
                        $btn.prop('disabled', false);
                        $progress.hide().text('');
                        return;
                    }

                    $progress.text('Removed 0 / ' + total + '...');
                    removeNextPage(total, 0);
                },
                error: function() {
                    removeFail('Could not start the removal. Please try again.');
                }
            });
        });
        
        // 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_plus_full';
        $allowed_sync_modes = array('short_only', 'short_fallback_full', 'short_plus_full');
        if (!in_array($sync_mode, $allowed_sync_modes, true)) {
            $sync_mode = 'short_plus_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;
    }
}


```
