=== AI eShop Optimizer ===
Description: Adaptive productivity, conversion & retention for eshops and content sites. Anthropic/Voyage AI: messaging, recommendations, attribution, loyalty, merchandising.
Tags: ai-chat, content-recommendations, embeddings, conversational-ai, analytics
Requires at least: 5.7
Tested up to: 7.0
Requires PHP: 8.0
Stable tag: 5.2
Woocommerce tested up to: 10.7
License: GPLv3 or later
License URI: http://www.gnu.org/licenses/gpl-3.0.html

Adaptive productivity, conversion & retention for eshops and content sites. Anthropic/Voyage AI: messaging, recommendations, attribution, loyalty, merchandising.

== Description ==
# AI eShop Optimizer - AI Chat & Content Recommendations Plugin
Welcome to AI eShop Optimizer, the premier AI-driven solution for intelligent customer engagement powered by the latest AI models from Anthropic and OpenAI.

**Works with or without WooCommerce** - Perfect for:
- E-commerce sites with WooCommerce for product recommendations
- Corporate and content sites for intelligent chat assistance
- Merchant information sites that need AI-powered customer support

The plugin provides advanced AI chat capabilities with semantic search powered by state-of-the-art embedding engines. For WooCommerce sites, it also enables product recommendations through our graph-database powered service at https://eshop-optimizer.com.
Our advanced AI tools uncover latent patterns and consumer preferences, empowering you with strategic upsell and cross-sell propositions.
The plugin also enables you to import with one click our recommendations - or any product recommendations in a csv file that conforms to our format - and to also monitor their performance using google UTM tags (which you may also use to monitor your own recommendations performace).

## Features
### AI Product Recommendations
- Harness the power of a semantic graph database for unmatched product pairing suggestions.
- Dive deep into your sales data to extract bespoke upsell and cross-sell opportunities.
- Beta-test participants reported a remarkable 57%+ annual surge in sales.
- Privacy-centric: Opt out of sharing product and category names and product prices with limited impact to the quality of the recommendations.
- Effortlessly back up and export current Upsells and Cross-sells.
- Leverage Google GA4 insights to gauge the success of your recommended pairings.

### Products for the Same Needs
- Automatically recommend products that fulfill the same customer needs
- Uses your product's need attributes (pa_need taxonomy) to find matching products
- Ranks suggestions by pre-computed sales performance from the product catalogue
- Intelligently excludes existing upsells and cross-sells to avoid duplicates
- Stores up to 6 optimized suggestions per product for fast retrieval
- Displays prominently on product pages (appears first, before other recommendations)
- Multi-tier caching for optimal performance (Object Cache + Database)
- Generate suggestions as part of Operational Efficiency workflow

### Insights Chat — Claude-powered (NEW in 5.0)
- Ask your shop questions in plain language from inside the WordPress admin
- Powered by the AI Chat Anthropic key you already have — no separate subscription
- 33 purpose-built Claude data abilities resolved automatically via the WordPress Abilities API
- 11 categorized accordion groups of suggestion chips — Customers, Brand portfolio, Recommendation rails, Attribution & archives, Product needs audit, Star ratings, Content & blog, Cross-skill, Store analytics, Promotions / launches / sales, Newsletters & campaigns
- Cross-cuts orders, products, attribution, recommendations, ratings, blog engagement, and customer profiles
- Stays inside WooCommerce — no third-party BI subscription, no data export

### Joint Session × Attribution Analytics (NEW in 5.0)
- Bridge between the Session Tracker (engagement) and the Attribution Engine (conversion) — both keyed off the same aieo_session_id cookie
- Blog-post attribution — clicks from blog posts to products now attribute correctly with the originating post_id
- Engagement-bucket buy-probability — empirical P(cart-add) per (scroll-quartile × time-quartile × mouse-activity) bucket per product
- Abandoned-cart triage, cart-removal analysis, rating × conversion correlation, need × conversion correlation
- Pre-aggregated daily rollup tables keep chat answers in single-digit milliseconds regardless of history depth

### Insights Remote DB Streaming (NEW in 5.0, Pro)
- Stream raw analytics events to your own operator-owned MariaDB / MySQL for unbounded BI access
- Reuses the existing ERP connection registry — same encrypted credentials, same audit trail
- Configurable export frequency (15 min / hourly / daily) with per-table lag dashboard
- Local-purge failsafe — hot rows are not deleted until the remote confirms receipt
- Net stable local database footprint ~1.1 GB year-over-year

### Star Ratings → SEO Schema (NEW in 5.0)
- AggregateRating JSON-LD automatically bridged into AIOSEO, Yoast, and RankMath via their schema filters
- Fallback head-injected JSON-LD when no SEO plugin is detected
- Per-feature enable/disable toggle on the Star Ratings admin page
- Surface customer ratings to Google Rich Results without manually configuring each SEO plugin

### Custom Slots + Tolstoy + Recommendations Ordering (NEW in 5.1)
- Drag-and-drop "Recommendations Ordering" card on the e-shop Manager dashboard reorders every recommendation rail (Up-sells / Cross-sells / Related / Recently Viewed / Products for the same needs) and any operator-defined Custom Slot, with a per-row Show toggle to hide rails without removing them
- Custom Slots host arbitrary content alongside the built-in reco rails — two kinds per slot:
  - Tolstoy: paste a widget id + account UUID; AIEO assembles the `<tolstoy-widget>` tag and defer-loads the gotolstoy.com CDN script once per page
  - HTML / code: rich-text WYSIWYG (TinyMCE) with a Code tab, accepts any HTML, embed scripts, image tags, or WooCommerce shortcodes (e.g. `[products limit="6" orderby="popularity"]`)
- Per-slot title with show/hide toggle — renders with the same heading + underline styling as the built-in "Recently Viewed Products" / "Related Products" titles
- Cross-tab Tolstoy attribution — clicks from a Tolstoy carousel that lead to a cart-add are recorded as `source='tolstoy'` in wp_aieo_addcart_events with `source_meta = {slot_id, tolstoy_widget_id, clicked_url}` so reports can pivot on widget, carousel, or source product
- Works on BOTH FSE block themes (via the `.ff-recommendations-cluster` flex container + inline CSS `order:` rules) AND classic themes (via dynamic re-prioritisation of WooCommerce `woocommerce_after_single_product_summary` action hooks)

### IAPI (Interactivity API) — WC Cart / Checkout block parity (NEW in 5.1)
- Full integration with the modern WooCommerce block-based cart and checkout (driven by WordPress @wordpress/interactivity)
- Side-cart, Swatches multi-select, Sticky Add-to-Cart, Wishlist, Star Ratings, Free-Shipping Display, Recommendations attribution all work on both surfaces — block-cart/block-checkout AND legacy shortcode-cart/shortcode-checkout
- AIEO_DMM_Swatches_Runtime supports dual-mode enqueue (`@aieo/swatches-iapi` module when IAPI is on, jQuery bundle otherwise) with a single DOM contract
- WC Store API (`wc/store/cart`) endpoints recognised by the side-cart, attribution log, and waitlist subscribe flows so block-checkout actions are captured the same as classic checkout
- AIEO Custom Slots, Free-Shipping Display, and Trust Badges register their bridge-block render paths inside `woocommerce_blocks_loaded` so they're available in block-themed cart/checkout templates via the Site Editor

### Floating Mini-Cart + Free-Shipping Bar (NEW in 5.0)
- Two-column floating mini-cart styled after the Rey theme — left column recommends "You might like", right column shows Shopping Bag / Recently Viewed
- Free-shipping progress bar right under the tab header
- 500 ms debounced quantity AJAX — qty changes feel instant, no full cart recalculation on the server
- Session-level HTML cache (30 s TTL); WC fragments integration keeps every other widget in sync
- Sticky Add-to-Cart bar for product pages

### Pricing Engine + Conversion Boosters (NEW in 5.0)
- Per-role price overrides via CSV upload, with batch validation
- Brand-level % discounts with start/end-date windows
- Loyalty class definitions + per-user assignments
- Stacking recipe: Role Pricing → Brand Discount → Loyalty Class — each customer sees the strongest applicable price
- Brand-based free-gift offers (cart subtotal threshold per brand)
- Configurable exit-intent modal with checkout-specific variant

### Marketplace Connectors & Shipping (NEW in 5.0)
- Marketplace Order Importer — Skroutz / e-shop / Amazon orders flow into WooCommerce as native orders so attribution, stock, customer profiles, and fulfillment stay unified
- Per-vendor rotatable webhook tokens + configurable SKU lookup strategy
- Streaming marketplace feed generator (XML / CSV) for 35k-product catalogues
- Greek + Cypriot Shipment Tracking providers (replaces the WC plugin's US/UK/Canada/Germany defaults)
- Smart Shipping Label — postcode-less carts see "Carrier (Από €X.XX)" minimum rate so customers know shipping isn't free without seeing a misleading default

### Customer Intelligence + Web Push (NEW in 5.0)
- wp_aieo_customer_intelligence keyed by eponymous_id — omnichannel customer view (eshop + in-store) is the single source of truth
- Behavioural segments — Top customers, Lost cohort, Lookalikes, Abandoned-cart, reactivation
- Triggered web-push flows — welcome, reactivation, price-drop, back-in-stock — with full dispatch log + click attribution
- Customer Survey Intelligence — Gravity Forms ingest + 7 high-signal metrics (NPS class, satisfaction, priorities, discovery channel, gift preferences, personal profile) + composite VoC score
- "Notify me when back in stock" Waitlist with automatic stock-watcher emails
- Wishlist analytics — most-wishlisted products, surfaces, and pages driving adds

### AI-Powered Chat (FREE)
- **Support for latest AI models from Anthropic Claude and OpenAI:**
  - Claude Opus 4.1, Claude Sonnet 4.5, Claude Haiku 4.5
  - GPT-5, GPT-4, GPT-o1, GPT-3.5
- **Advanced embedding engines for semantic product search:**
  - Voyage AI: voyage-3.5-large, voyage-3.5-lite, voyage-3-lite, voyage-finance-2
  - OpenAI: text-embedding-3-large, text-embedding-3-small, text-embedding-ada-002
- Customizable chat templates for different use cases
- Smart product search and recommendations powered by AI embeddings
- Product catalog integration with semantic similarity matching
- Context-aware responses using customer behavior data
- Customizable chat appearance with multiple themes (Rounded/Square)
- Dynamic color customization for branding
- Session management and chat history tracking
- Floating chat widget with adjustable positioning
- Mobile-responsive design

### Advanced Session Analytics
- **Custom Class-Based Event Tracking** - Track clicks on any element using custom CSS selectors
- **Click Event Throttling** - Prevent database flooding while maintaining accurate click counts
- **Cookie Consent Bypass Mode** - Toggle GDPR compliance for immediate tracking or compliance-first approach
- **Product Image Click Tracking** - Special tracking for product images with debounce to prevent duplicate events
- **Anti-Double-Counting** - Custom rules take precedence over standard tracking
- **Automatic Cache Busting** - Version strings with variable lengths for aggressive cache invalidation
- **Multi-Layer Cache Compatible** - Works with Nginx, Varnish, REDIS, WP Rocket, Cloudflare


## How to Use

- Export and Back-Up Current Pairings
   Safely export existing upsells and cross-sells, which doubles as a reliable back-up. The Pro version also takes your current selections into account, potentially enhancing the AI's output.

- Accelerated Order Export (Enabled HPOS Required)
   Swiftly export up to 100,000 order items. The Pro version lifts the cap on orders, including comprehensive details like Order ID, Product ID, sequence, and more.
   Exclude product titles and prices at will.
   Maintain customer anonymity by withholding CustomerIDs, albeit with a slight compromise on recommendation precision.
   Opt for a seasonal sales analysis, focusing on trends pertinent to the current time of year.
   Refine Your Data with Our AI Engine
   Register at eshop-optimizer.com and submit your data. Within moments, receive refined upsell and cross-sell strategies for your leading products. Full catalog analysis available with the Pro version.
   eshop-optimizer.com respects your privacy and adheres to strick privacy guidelines. Our company's, Oxford Metadata Ltd, privacy provisions has been approved by both Google and Facebook. For further details please visit: https://eshop-optimizer.com/compliance  

- Import Tailored Upsell and Cross-sell Strategies
   Implement the AI-crafted upsell and cross-sell suggestions via an easy-to-upload CSV file.

- Witness Enhanced Sales
   Marvel at the accuracy of our AI-driven recommendations and observe how they can boost your sales figures. We're so confident in our service that we offer free initial analyses - we believe you'll be eager for more and enthusiastic to spread the word!
      Experience the relevance of our recommendations and discover how AI can improve your store's sales. We offer free analyses, and we are confident that you'll want more and share our plugin with your friends!

For any queries or support, contact us at [support@eshop-optimizer.com](mailto:support@eshop-optimizer.com).

---
Website: (https://eshop-optimizer.com)


== Installation ==

Extract the contents of this plugin zip file into your wp-content/plugins/ directory locally.
Upload the extracted folder to your website.
Navigate to wp-admin/plugins.php on your dashboard.
Find 'AI eShop Optimizer' and activate the plugin.
Alternatively, install directly through WordPress:

Go to the 'Plugins' menu in WordPress.
Click 'Add New' and search for 'AI eShop Optimizer.'
Install and activate directly from your dashboard.

== Changelog ==

= 5.0 - 2026-05-15 =
**MAJOR RELEASE: Insights Chat (Claude-powered), Joint Session × Attribution Analytics, Four-Layer Retention, and the Pro Tier**

**Insights Chat — Claude-powered, in-admin**
* NEW: Tools → Insights Chat — ask your shop questions in plain language using the AI Chat Anthropic key you already have
* NEW: 33 purpose-built Claude data abilities (registered through the WordPress Abilities API)
* NEW: Categorized accordion suggestion chips across 11 question groups — Customers, Brand portfolio, Recommendation rails, Attribution & archives, Product needs audit, Star ratings, Content & blog, Cross-skill, Store analytics, Promotions / launches / sales, Newsletters & campaigns
* NEW: Tool-use loop with bidirectional Anthropic-safe tool naming
* NEW: All chips and abilities respect manage_woocommerce capability

**Session Tracker × Attribution Engine Integration**
* NEW: Cross-cuts engagement (session tracker) with conversion (attribution engine) via a shared aieo_session_id cookie
* NEW: Blog-post attribution — clicks from blog posts to products now carry source=blog_post + source_meta.post_id
* NEW: Engagement-bucket buy-probability — empirical P(cart-add) per (scroll-quartile, time-quartile, mouse-activity) bucket
* NEW: Abandoned-cart triage, cart-removal analysis, rating × conversion correlation, need × conversion correlation
* NEW: 11 new joint-analytics abilities backing the chat suggestion chips
* Improved: Attribution Engine now respects Session Tracker's consent state (GDPR alignment)

**Insights Remote DB Streaming + Four-Layer Retention**
* NEW: Insights Remote DB Settings tab — stream raw events to your own operator-owned MariaDB / MySQL via the existing ERP connection registry
* NEW: Configurable export frequency (15 min / hourly / daily) with per-table lag dashboard and dry-run "Test export"
* NEW: 5 pre-aggregated daily rollup tables so the chat abilities never hit raw event tables — millisecond responses regardless of history size
* NEW: aieo_aggregate_rollups nightly cron + unified aieo_archive_run weekly cron
* NEW: Tightened hot retention — 14 days (sessions), 30 days (reco events), 365 days (cart-adds)
* NEW: Local-purge failsafe — hot rows are NOT deleted until the remote-export bookkeeping confirms receipt
* Improved: Net stable DB footprint ~1.1 GB year-over-year (was unbounded — projected 6-8 GB by year 2)

**Star Ratings → SEO Schema Bridge**
* NEW: AggregateRating JSON-LD bridged into AIOSEO, Yoast, and RankMath via their schema filters
* NEW: Fallback head-injected JSON-LD when no SEO plugin is detected
* NEW: Per-feature enable/disable toggle on the Star Ratings admin page

**Floating Mini Side-Cart, Sticky ATC & Free-Shipping Bar**
* NEW: Two-column floating mini-cart — left: "You might like" recommendations, right: Shopping Bag / Recently Viewed tabs with the free-shipping progress bar right under the tab header
* NEW: 500 ms debounced quantity AJAX → 400-byte JSON → optimistic client-side recompute — qty changes feel instant, no full cart recalculation on the server
* NEW: Session-level HTML cache keyed by cart_hash (30 s TTL); WC fragments integration keeps every other widget in sync
* NEW: Side-cart recommendations sourced from the DMM product-bundle endpoint — same cached HTML powers the product page AND the mini-cart
* NEW: Sticky Add-to-Cart bar (DOM classes + JS global kept verbatim so existing CSS/JS bundles work without modification)
* NEW: Free-Shipping admin — threshold + product / brand exclusions, with the package-rates filter that strips free shipping when any excluded item is in the cart

**Pricing Engine — Role Pricing, Brand Discounts, Loyalty Classes**
* NEW: Per-role price overrides via CSV upload (staged batch validation → AJAX batches); mirrors into the legacy om-role-pricing table so existing storefront integrations keep working byte-for-byte
* NEW: Brand-level % discounts with optional start/end-date windows
* NEW: Loyalty class definitions + user assignments — applied in the global pricing recipe by AIEO_DMM_Pricing_Engine
* NEW: Stacking recipe: Role Pricing → Brand Discount → Loyalty Class — each customer sees the strongest applicable price

**Conversion Boosters — Brand Gifts & Exit Intent**
* NEW: Brand-based free-gift offers — gift (price = 0) auto-added when the cart subtotal of the offer's brand(s) crosses min_subtotal within the date window
* NEW: Configurable exit-intent modal — fires on cursor exit-intent after a warm-up delay; two HTML bodies (generic site-wide + upgraded checkout-specific); optional restriction to checkout-only or anonymous visitors; session-storage dismissal
* NEW: Legacy `exit-intent-offer` standalone plugin auto-imported on first read and deactivated — no manual migration

**Marketplace Connectors & Shipping**
* NEW: Marketplace Order Importer — pulls Skroutz / e-shop / Amazon orders into WooCommerce as native orders so attribution, stock, customer profiles, and fulfillment stay unified. Per-vendor webhook URLs with rotatable tokens, configurable SKU strategy, default order status per vendor
* NEW: Streaming Marketplace Feeds generator — handles 35k-product catalogues without blowing memory; include/exclude rules by product or brand, XML or CSV output, per-feed cron registration on save
* NEW: Shipment Tracking provider list cleaned up — drops US/UK/Canada/Germany defaults, adds Greek + Cypriot carriers + Stoferno.gr
* NEW: Smart Shipping Label — guests / postcode-less carts see "Carrier (Από €X.XX)" with the minimum rate so they know shipping isn't free without seeing a misleading default. Free-shipping carts hide method prices and the generic "Free shipping" pseudo-method (customer still picks a real carrier, just with €0). Greek "184 53" postcodes auto-normalize to "18453"

**Customer Intelligence + Web Push + Voice-of-Customer**
* NEW: wp_aieo_customer_intelligence — keyed by eponymous_id (AIEO's canonical customer identity), with secondary wp_user_id + source_table columns so anonymous → logged-in stitching has a single home
* NEW: Chunked recompute stored procedure over AIEO's pre-built snapshot tables — omnichannel customer view (eshop + in-store merged) is the source of truth
* NEW: Behavioural segments — Top customers, Lost cohort, Lookalikes, Abandoned-cart, reactivation
* NEW: Triggered web-push flows — welcome, reactivation, price-drop, back-in-stock — with full dispatch log + per-subscriber delivery + click attribution
* NEW: Customer Survey Intelligence — Gravity Forms 18 + 20 ingest (real-time hook + daily cron safety net + manual button), 7 high-signal metrics (NPS class, overall satisfaction, professional-verified, personal priorities, discovery channel, gift category preference, personal profile), composite voc_score (0-100)
* NEW: "Notify me when back in stock" Waitlist — out-of-stock product pages render the signup form, stock watcher emails subscribers when stock flips back; one-shot migration from the legacy PPE waitlist table
* NEW: Wishlist analytics — read-only admin views: which products are most-wishlisted, which surfaces drive adds, which pages / categories convert to wishlist

**Pro Tier — Frosted-Glass Overlays on 13 Admin Tabs**
* NEW: Apple-glass overlay with PRO badge, feature-specific title + description + bullets, and "Upgrade to Pro" CTA
* NEW: Pro-locked tabs — Attribution Dashboard, Advertising Campaigns, Web Push, Customer Intelligence Surveys, Insights Chat, Shipment Cost Reports, Insights Remote DB Settings, Action Scheduler Cleanup, ERP Bridge, ERP Database, Order Documents & Couriers, Marketplace Order Importer, Branch Stock Scanner, Order Cancellations
* Improved: Pro detection now honors BOTH paths — eshop-optimizer.com Pro membership OR a valid rooster.systems Content Connector API key (either is sufficient)
* Improved: Locked tabs do not execute heavy queries or expose credentials for non-Pro operators

**Attribution Menu Restructure**
* NEW: New top-level "Attribution" menu group containing the Dashboard and the Advertising Campaigns admin
* NEW: Campaigns auto-populate from utm_campaign — no manual correlation needed; new campaign slugs appear as auto_draft rows after the next dashboard load
* Improved: Advertising Campaigns moved from Pricing & Offers into Attribution (same dropdown as the dashboard it shares data with)

**Greek Translation Pass + i18n Hygiene**
* NEW: ~70 new Greek (el) translation strings covering Pro overlays, suggestion chips, and admin navigator labels
* Improved: All 11 admin-navigator group labels wrapped in __()
* Improved: 117 i18n errors fixed across the plugin

**Plugin-check & Security Hygiene**
* Improved: Plugin-check ERRORs reduced from 132 to 0 (excluding the agreed-upon DB stored-procedure exceptions acknowledged by the WordPress.org plugin review team)
* Improved: All AJAX handlers routed through a centralised nonce verifier
* Improved: Every new DB-touching ability has min/max input bounds and sanitize_key on all string keys

**Architectural Improvements**
* NEW: Module V2 manifest pattern (data/admin/frontend/compute split scaffolding — opt-in per module migration)
* NEW: .distignore file at plugin root keeps internal docs, dev tooling, and the Claude Code skill pack out of the wp.org distribution package
* NEW: docs/BUILD_AND_DISTRIBUTION.md documents the SVN deploy workflow

**Operator Notes**
* On first activation of 5.0 the new aggregate rollup tables are created and the nightly aieo_aggregate_rollups cron begins back-filling history — expect 1-3 nightly runs before the chat abilities reach full historical coverage
* The 13 Pro-locked tabs are visible to free-tier operators with the frosted overlay; underlying database tables are still created so a later Pro upgrade has zero migration cost
* No customer-facing front-end changes — this is an admin-side and analytics-side release

= 4.2 - 2026-01-28 =
**FEATURE UPDATE: Products for the Same Needs - Need-Based Recommendations**

**Products for the Same Needs**
* NEW: Automatic product suggestions based on matching customer needs (pa_need attribute)
* NEW: Finds products sharing primary, secondary, or additional needs with the current product
* NEW: Rankings powered by pre-computed TotalItemSales from product catalogue for maximum performance
* NEW: Smart exclusion of existing upsells and cross-sells to prevent duplicate recommendations
* NEW: Stores up to 6 optimized suggestions per product in dedicated database table
* NEW: Display checkbox in Display Preferences: "Please display Products for the same needs"
* NEW: Generation checkbox in Operational Efficiency: "Please generate products with the same needs"
* NEW: Displays first on product pages (priority 10) before upsells, cross-sells, and related products
* NEW: Multi-tier caching support via AIEO Recommendations Cache (Object Cache + Database)
* NEW: Empty sections automatically hidden when no matching products exist
* Improved: Seamless integration with existing AJAX lazy loading infrastructure
* Improved: Skeleton loading animation while fetching recommendations

**Technical Details**
* NEW: wp_aieo_product_need_suggestions database table for persistent storage
* NEW: AI_eShop_Need_Suggestions class for generation logic
* NEW: same_needs added to cacheable recommendation types
* NEW: Generation runs as final step in Operational Efficiency batch processing

= 4.1 - 2025-12-06 =
**FEATURE UPDATE: Advanced Analytics, Conversation Memory, Business Knowledge Base & Performance Optimizations**

**Advanced Statistics with Heatmap Drill-downs (Pro)**
* NEW: Product category performance analytics with visual heatmap drill-downs
* NEW: Brand-level performance tracking with interactive heatmaps
* NEW: Click-to-drill functionality for exploring category and brand hierarchies
* Improved: Visual analytics for understanding product performance patterns

**Conversation Memory**
* NEW: AI chat now remembers previous questions within the same conversation
* NEW: Contextual follow-up responses that reference earlier discussion points
* Improved: More natural conversational flow with memory of user preferences mentioned earlier

**Business Information Knowledge Base**
* NEW: Site Identity configuration - define "What this site IS" and "What this site is NOT"
* NEW: Automatic WordPress tagline integration in AI context
* NEW: Prevents AI from misidentifying your business type (e.g., calling a clinic a "shop")
* NEW: Import existing page content as knowledge base entries (text-only, HTML stripped)
* NEW: WooCommerce Shipping Zones integration - automatically sync all shipping rates and locations
* Improved: Zone-centric shipping data structure for accurate location-based queries

**User Feedback System**
* NEW: Thumbs up/down rating for each AI response
* NEW: User feedback stored for continuous improvement analysis
* NEW: Rating data helps identify areas for answer quality improvement

**JavaScript Performance Optimizations**
* NEW: Lazy initialization for session tracker - only activates on user interaction (click, scroll, mouse move)
* NEW: Lazy initialization for floating chat widget - full initialization deferred until button click
* NEW: Conditional asset loading - chat CSS/JS only loads when floating chat is enabled or shortcode is present
* NEW: Vanilla JS trigger button display for faster rendering (no jQuery dependency for initial display)
* Improved: Eliminated ~4s page load delay from session tracker
* Improved: Reduced page weight on pages without chat functionality

**WooCommerce Table Rate Shipping Compatibility**
* NEW: Full compatibility with WooCommerce Table Rate Shipping plugin
* NEW: Automatic import of shipping zones, rates, and conditions
* NEW: Zone-centric data structure with all postal codes and shipping methods per zone
* NEW: AI can now accurately answer "How much is shipping to [postal code]?" questions
* Improved: Only active shipping methods are imported (inactive methods excluded)

= 4.0 - 2025-11-27 =
**MAJOR UPDATE: Dynamic AI Model Support + Database Collation Fixes + Anonymous User Chat Logging**

**Dynamic AI Model Registry**
* NEW: Dynamic model selection from database - over 50 AI model flavours now available
* NEW: All Anthropic Claude models (Claude 4, Opus 4.5, Sonnet 4.5, Haiku 4.5 and all versions)
* NEW: All OpenAI models (GPT-5.1, GPT-5, GPT-4, GPT-o1, GPT-3.5 and all variants)
* NEW: All embedding models (Voyage AI, OpenAI) dynamically loaded from wp_aieo_ai_models table
* NEW: Model dropdowns in admin panel now populate directly from database registry
* Improved: Adding new AI models no longer requires code changes - just update the database

**Database Collation Compatibility**
* Fixed: Core product attributes table now uses correct charset collation
* Fixed: Core product vitals table now uses correct charset collation
* Fixed: Core variation vitals table now uses correct charset collation
* Fixed: All AIEO tables now consistently use utf8mb4_uca1400_ai_ci (or database default)
* Improved: Full compatibility with MariaDB 11.4, MariaDB 11.8, MySQL 5.7, and MySQL 9
* Improved: Removed problematic BINARY comparison in stored procedures

**Anonymous User Chat History**
* Fixed: Chat exchange logging now works correctly for anonymous (non-logged-in) users
* Fixed: Session tracking properly handles anonymous user conversations
* Improved: Re-ranking system properly logs all chat exchanges regardless of user status

**Translation Improvements**
* Fixed: Frontend chatbox now correctly loads translations from plugin languages directory
* Fixed: Translation loading priority adjusted for earliest hook execution
* Improved: Fallback translation loading from multiple locations

**API Key Validation & Credit Check**
* NEW: "Validate API Keys & Check Credits" button to verify all configured API keys
* NEW: Detects exhausted credits and displays warning with direct links to billing dashboards
* NEW: Quick access to Anthropic, OpenAI, and Voyage AI billing management pages
* NEW: Status indicators show Valid, Invalid, No Credits, or Not Configured for each provider

**Database Optimization**
* NEW: Added 6 missing Graph UUID indexes for optimal export performance (20 indexes total, up from 13)
* NEW: Indexes for all 9 UUID columns used in graph frequency calculations
* NEW: Product stats filter index for faster aggregation queries

= 3.6 - 2025-11-13 =
**MAJOR UPDATE: MySQL 8 Full Compatibility + Advanced Search Re-ranking + Embedding Error Detection**

**Advanced Search Re-ranking System**
* NEW: Configurable re-ranking weights for hybrid search results - control the balance between semantic similarity and keyword matching
* NEW: Dedicated "Re-ranking Weights" configuration section in AI Chat settings with real-time preview
* NEW: Semantic similarity weight slider (0-100%) - adjust how much AI embeddings influence search results
* NEW: Keyword matching weight slider (0-100%) - adjust how much exact text matches influence results
* NEW: Automatic normalization - weights always sum to 100% for perfect score balancing
* NEW: Visual feedback showing current weight distribution with color-coded indicators
* NEW: Three preset configurations: Semantic-focused (70/30), Balanced (50/50), Keyword-focused (30/70)
* NEW: Database schema migration for re-ranking weights with default 50/50 balanced configuration
* Improved: Search results now combine embedding similarity scores with keyword match scores using configurable weights
* Improved: More relevant search results by allowing merchants to tune for their specific product catalog
* Improved: Better handling of product variations vs parent products in search rankings

**Embedding Error Detection & Reliability**
* NEW: Comprehensive embedding failure tracking system for monitoring API reliability
* NEW: Real-time failure statistics showing success rate, average latency, and failure breakdown by error type
* NEW: Automatic retry logic with exponential backoff for transient API errors (rate limits, timeouts, network issues)
* NEW: Smart failure categorization: Rate Limits, Timeouts, Network Errors, Invalid Input, and Unknown Errors
* NEW: Failure trend analysis showing time-series data for the last 30 days
* NEW: Visual error rate graphs with color-coded severity indicators (green <1%, yellow 1-5%, red >5%)
* NEW: Detailed error logs with timestamps, error types, and affected content IDs
* NEW: Automatic recovery suggestions based on error patterns
* NEW: Database table wp_aieo_chat_embedding_failures for persistent failure tracking
* NEW: Failed items automatically flagged for priority retry in next training batch
* Improved: Embedding training now shows detailed progress including retry attempts
* Improved: API quota management with intelligent retry delays (60s for rate limits, 30s for timeouts)
* Improved: Better error messages during training with actionable recommendations
* Fixed: Embedding batch processing now handles partial failures gracefully
* Fixed: Training no longer stops on single item failures - continues with remaining items

**MySQL 8 & Database Compatibility (100% MySQL 8 Support)**
* NEW: Complete MySQL 8.0+ compatibility - plugin now works flawlessly on both MariaDB 11.4+ and MySQL 8.0+
* NEW: MySQL 8-specific database performance optimization with histogram statistics support
* NEW: Database Performance Optimization section now auto-detects MySQL 8 vs MariaDB and applies appropriate optimizations
* NEW: MySQL 8 histogram-based query planning for 20-30% faster customer and product statistics
* NEW: Descending indexes for MySQL 8 to optimize recent-order queries without reverse scans
* Fixed: DROP INDEX IF EXISTS syntax errors on MySQL 8 - now uses INFORMATION_SCHEMA checks (100% compatible)
* Fixed: CREATE OR REPLACE FUNCTION syntax errors - converted to MySQL 8 compatible drop-then-create pattern
* Fixed: Binary logging privilege handling - graceful degradation when log_bin_trust_function_creators is disabled
* Fixed: All 52+ MariaDB-specific syntax instances converted to cross-compatible code
* Improved: Stored functions now skip creation gracefully on MySQL 8 with binary logging restrictions
* Improved: Helper functions (aieo_drop_index_if_exists, aieo_drop_function_if_exists) for database compatibility
* Performance: Expected 38-48% improvement on MySQL 8 after applying database optimizations (5-6 minutes vs 9.5 minutes for 37K products)
* Performance: 13 composite indexes + histogram statistics on 6 key columns for optimal query performance

**Additional Improvements**
* Improved: Enhanced logging throughout embedding and search processes for better debugging
* Improved: Better error handling and user feedback during AI Chat configuration
* Improved: Database query optimization for embedding statistics and search queries
* Improved: Code organization with separate MySQL 8 optimization file for maintainability
* Fixed: Variation enrichment now properly handles missing parent product data
* Fixed: Embedding statistics now accurately reflect training status across all content types
* Updated: Documentation with MySQL 8 compatibility notes and performance tuning recommendations

= 3.5.2 - 2025-11-07 =
* Fixed: Welcome bubble positioning now follows floating widget position setting (bottom-left, bottom-center, bottom-right)
* Fixed: Welcome bubble positioning respects mobile position setting independently
* Fixed: Welcome bubble arrow positioning for all positions (left, center, right)
* Fixed: Chat close button height override for themes with aggressive button styling
* Fixed: Text domain loading for translations - now works on all WordPress versions for local development
* Chat Addon: Updated to version 3.5.2 with improved localization and UI fixes

= 3.5.1 - 2025-11-07 =
* Fixed: Fatal error on non-WooCommerce sites - AI Chat now properly checks for WooCommerce before calling product-specific functions
* Chat Addon: Updated to version 3.5.1 with improved compatibility for standalone WordPress sites

= 3.5 - 2025-11-07 =
* NEW: Advanced Session Analytics Infrastructure - Track customer attention and engagement like orders with detailed journey analytics
* NEW: Position Analytics - Automatically identify landing pages, exit pages, and bounce events for instant engagement insights
* NEW: Attention Economics Metrics - Measure time-on-page, scroll depth, click counts, and product revisits (hesitation metric)
* NEW: Conversion Funnel Tracking - Monitor checkout step progression from cart to order completion with drop-off point identification
* NEW: Journey Sequencing - Track event order and product view patterns for understanding customer behavior paths
* NEW: Custom Class-Based Event Tracking - Define custom CSS selectors to track clicks on any element (buttons, swatches, divs, images, etc.)
* NEW: Click Event Throttling - Optional throttling to prevent database flooding while maintaining accurate click counts
* NEW: Cookie Consent Bypass Mode - Toggle GDPR consent requirement for immediate tracking or compliance-first approach
* IMPROVED: Product image click tracking with 5-second debounce to prevent duplicate lightbox events
* IMPROVED: Custom tracking rules take precedence over standard tracking to prevent double-counting
* IMPROVED: JavaScript code generation is "baked in" as inline scripts for better performance
* IMPROVED: Automatic version bumping with variable-length strings for aggressive cache busting
* NEW: Multi-Layer Cache Compatibility - Session tracker now fully compatible with Nginx, Varnish, REDIS, WP Rocket, and Cloudflare
* NEW: Session-to-Order Linkage - Connect customer browsing sessions directly to WooCommerce order completions
* Improved: Client-side session generation for cache-proof tracking across aggressive caching environments
* Improved: Enhanced migration system with comprehensive schema validation for all attention analytics columns
* Improved: Archive table management now transfers all 20 analytics fields during scheduled cleanup
* Improved: Database indexes optimized for attention analytics queries (7 new indexes for performance)
* Fixed: Session schema migration now correctly detects missing attention analytics columns
* Fixed: Clean installations now create complete analytics schema with all 20 columns from activation

= 3.4 - 2025-11-06 =
* NEW: Configurable batch size parameter for embedding training - merchants can now adjust batch size (1-999 items) to control training speed and API rate limits
* NEW: Dynamic embedding statistics for all post types - stats section now automatically displays all custom post types with published content (was previously limited to Products/Pages/Posts)
* Fixed: Voyage AI taxonomy embeddings batch processing - resolved associative array key mapping issue that caused "Unknown API error" when processing categories and tags
* Improved: Unified batch processing implementation - both OpenAI and Voyage AI now use consistent associative array format for better code maintainability
* Chat Addon: Updated to version 3.4 

= 3.3.3 - 2025-11-05 =
* NEW: Category-scoped AI Chat - Users can select specific product categories, post categories, or CPT taxonomies to focus chat responses
* NEW: Smart Category Auto-Selection - AI Chat automatically defaults to the top-level parent category of the current product/archive page (e.g., opens scoped to "Skincare" when viewing a product in "Skincare > Face Creams")
* NEW: Related Products Slider in Chat - Visual product recommendations displayed in elegant slider format within chat responses
* NEW: Product Needs Attribute System - Merchants can define customer needs that products fulfill (primary, secondary, and additional needs)
* NEW: Heavily Weighted Needs in Embeddings - Primary and secondary needs get maximum emphasis in AI embeddings for accurate need-based matching
* NEW: Select All/Deselect All buttons for data analysis checkboxes for easier workflow management
* Improved: Object cache performance optimizations for category lookups and data retrieval
* Improved: More customization options for chat appearance and behavior
* Improved: Category hierarchy now uses dedicated hierarchy table instead of WooCommerce taxonomies for consistent cross-post-type support
* Fixed: Various minor styling fixes for better visual consistency across admin panels
* Chat Addon: Updated to version 3.3.3 with full category filtering and needs-based semantic search

= 3.3.2 - 2025-11-04 =
* Fixed: Embedding training duplicate product ID issue - eliminated infinite loops during batch processing in some prioritization options
* Fixed: AI Chat warning modal persistence - now properly removes after data analysis completion
* Improved: Database query optimization - added DISTINCT/GROUP BY to all ID-returning queries for duplicate prevention
* Improved: Performance indexes added to embeddings table (lookup_idx, stats_idx) for 10-20x faster queries
* Improved: Object cache bypass during critical embedding storage operations to prevent interference
* Improved: Multi-layer duplicate protection using array_unique() at function entry/exit points
* Improved: Index existence checks now use static variables instead of transients (no wp_options writes)
* Improved: All 8 priority metrics now supported with optimized GROUP BY queries
* Chat Addon: Updated to version 1.1.1 with sessionStorage support for warning state persistence

= 3.3.1 - 2025-11-03 =
* Fixed: Admin panel styling issues - cleaned up overlapping CSS rules and consolidated chat admin styles
* Fixed: Reduced plugin description to under 150 characters for WordPress.org compliance
* Improved: Chat addon CSS version bumped to force cache refresh for style updates

= 3.3 - 2025-11-03 =
* NEW: Plugin now works standalone without WooCommerce - perfect for corporate sites and merchant information pages
* NEW: Intelligent menu placement - integrates with WooCommerce when available, standalone top-level menu otherwise
* NEW: Custom network icon for better visual identification in WordPress admin
* NEW: Customizable AI Chat input placeholder text in settings
* NEW: AI Chat tab warning now shows on hover for better user guidance
* Improved: Shortened menu labels ("AI Optimizer") to prevent UI wrapping on smaller screens
* Improved: Added descriptive submenu items with emoji icons for better navigation
* Improved: Updated to use future-proof Claude model alias (claude-sonnet-4-5)
* Improved: AI Chat warning only displays on WooCommerce sites (not needed for standalone content sites)
* Improved: AI Chat tab warning automatically refreshes after data analysis completes
* Fixed: Chat wrapper now properly fills custom popup width without margins
* Fixed: Send button arrow now points right (horizontally flipped)
* Fixed: JavaScript errors with e.target.closest() when clicking on text nodes in theme files

= 3.2.1 - 2025-11-02 =
* Fixed: Deduplication mode setting now saves correctly when changed via Training Mode dropdown
* Fixed: Product prioritization now correctly queries sales metrics from temp_orders table
* Fixed: Embedding statistics now accurately count only parent products (excludes individual variations)
* Fixed: All product queries now consistently filter by published status for accurate counts
* Fixed: Training and statistics now use matching data sources to prevent count mismatches

= 3.2 - 2025-11-01 =
* NEW: Support for Pages and Posts in visual editors (Elementor, WP Bakery, TagDiv Composer) - AI Chat now extracts content from page builders
* NEW PRO: Process Automation feature - Schedule automatic data analysis and embedding updates (daily/weekly at custom times)
* NEW PRO: Contextual Metadata - Enhanced chat with device profile, browsing history, and user preferences for personalized recommendations
* NEW PRO: AI Session Tracker (Beta) - Track customer engagement depth, product interactions, and cart behavior with zero cost alternative to Google Analytics BigQuery
* Improved: Added helpful documentation links for product priority metrics
* Improved: Better HTML structure for configuration sections in AI Chat settings
* Improved: Enhanced visual consistency across admin panels
* Fixed: Posts & Pages configuration header now extends properly across full width
* Fixed: Various minor UI/UX improvements

= 3.1.2 - 2025-10-31 =
* NEW: Added referral links tracking for better affiliate program management
* Improved: Enhanced tracking capabilities for referral campaigns
* Improved: Better analytics for referral link performance

= 3.1.1 - 2025-10-30 =
* CRITICAL FIX: Fixed activation race condition where core product tables weren't created on first plugin activation
* CRITICAL FIX: Fixed "PROCEDURE already exists" errors during plugin activation by dropping procedures before creating them
* Fixed: Core tables now reliably created on initial activation without needing deactivate/reactivate
* Fixed: Stored procedures now recreate cleanly during activation without errors
* Fixed: Legacy stored procedures from older plugin versions now properly cleaned up during activation/deactivation
* Improved: More robust plugin activation process with idempotent procedure creation
* Improved: Complete database cleanup on deactivation (removes all procedures including legacy ones)
* Updated: Plugin tags to include AI Chat, OpenAI, Anthropic, Voyage, Multiple Embeddings, Reranking, Semantic Search

= 3.1 =
* NEW: Separate mobile and desktop widget positioning for optimal UX across devices
* NEW: Support for flexible dimension units (px, vh, %, vw) for responsive chat widget sizing
* Improved: Mobile chat widget responsiveness and input visibility
* Fixed: Chat widget positioning on mobile devices
* Fixed: Input box visibility on all screen sizes

= 3.0 =
* NEW: AI-Powered Chat feature with support for latest Anthropic Claude and OpenAI engines
* NEW: Support for cutting-edge AI models (Claude Opus 4.1, Claude Sonnet 4.5, Claude Haiku 4.5, GPT-5, GPT-4, GPT-o1, GPT-3.5)
* NEW: Advanced embedding engines for semantic search (Voyage AI: voyage-3.5-large, voyage-3.5-lite, voyage-3-lite, voyage-finance-2)
* NEW: OpenAI embeddings support (text-embedding-3-large, text-embedding-3-small, text-embedding-ada-002)
* NEW: Customizable chat templates for different use cases
* NEW: Product catalog integration with AI-powered semantic similarity matching
* NEW: Smart product search and recommendations powered by AI embeddings
* NEW: Customizable chat appearance with theme options (Rounded/Square)
* NEW: Dynamic color customization for complete branding control
* NEW: Session management and chat history tracking
* NEW: Floating chat widget with adjustable positioning
* NEW: Mobile-responsive chat design
* Improvement: WordPress coding standards compliance
* Improvement: Enhanced database query preparation
* Improvement: AI Session Tracker (Beta)
* Fix: Translation support improvements with proper translator comments
* Fix: Date/time functions now use timezone-safe gmdate()
* Fix: Chat input no longer inherits theme styles
* Fix: Various appearance issues

= 2.0 =
* Compatibility: Enhanced compatibility with MariaDB 11+ and MySQL 9.0
* Compatibility: Added support for PHP 8.4
* Fix: Removed hardcoded collation statements to use database defaults
* Fix: Prefixed admin CSS classes to prevent conflicts with other plugins
* Various minor bug fixes and improvements

= 1.0 =
* Initial release
