# ChoiceMate Documentation

## Table of Contents

1. [Introduction](#introduction)
2. [Features](#features)
3. [Requirements](#requirements)
4. [Installation](#installation)
5. [Quick Start Guide](#quick-start-guide)
6. [Configuration](#configuration)
7. [Usage](#usage)
8. [API Integration](#api-integration)
9. [Customization](#customization)
10. [Analytics](#analytics)
11. [Troubleshooting](#troubleshooting)
12. [API Reference](#api-reference)
13. [Developer Guide](#developer-guide)
14. [FAQ](#faq)
15. [Support](#support)

***

## Introduction

**ChoiceMate** is an AI-powered WordPress plugin that revolutionizes the WooCommerce shopping experience by providing intelligent product recommendation assistants. The plugin creates interactive question trees that guide customers through a personalized journey to find their perfect products.

Using OpenAI's GPT models, ChoiceMate analyzes your product catalog and automatically generates smart, contextual questions tailored to each product category. This eliminates choice paralysis and significantly improves conversion rates by helping customers find exactly what they need.

### Key Benefits

* **Increased Conversions**: Guide customers to their ideal products faster
* **Reduced Bounce Rate**: Engage visitors with interactive, helpful content
* **Automated Intelligence**: AI generates category-specific questions automatically
* **Data-Driven Insights**: Track customer preferences and behavior
* **Zero Manual Setup**: Plug-and-play solution with intelligent defaults

***

## Features

### 🧠 AI-Powered Question Generation

* Automatically analyzes product catalogs to create intelligent question trees
* Generates category-specific questions based on actual product attributes
* Supports both Dutch and English with automatic language detection
* Smart dynamic criteria that adapt to each product category

### 🎯 Intelligent Product Matching

* Advanced algorithm matches customer responses to ideal products
* Provides detailed reasoning for each recommendation
* Supports multiple recommendation formats (single choice, multiple choice, range)
* Customizable recommendation limits (1-10 products)

### 📊 Comprehensive Analytics

* Track customer interactions and completion rates
* Monitor conversion data and product performance
* Session tracking with detailed customer journey mapping
* Export analytics data for further analysis

### 🎨 Flexible Display Options

* Automatic widget display on category pages
* "Find Alternative" buttons on product pages
* Shortcode support for custom placement
* Fully customizable frontend text and styling

### ⚙️ Advanced Configuration

* Smart caching system to minimize API costs
* Performance optimization with configurable cache duration
* Database cleanup and maintenance tools
* HPOS (High-Performance Order Storage) compatibility

### 🔒 Security & Privacy

* Local data storage (GDPR compliant)
* No customer data sent to external APIs
* Secure API key management
* WordPress nonce verification for all AJAX requests

***

## Requirements

### WordPress Environment

* **WordPress**: 6.0.0 or higher
* **WooCommerce**: 7.0.0 or higher
* **PHP**: 8.0 or higher
* **MySQL**: 5.6 or higher

### External Services

* **OpenAI API Key**: Required for AI functionality
  * Sign up at [platform.openai.com](https://platform.openai.com)
  * GPT-3.5-turbo model used for cost efficiency
  * Typical cost: $0.001-0.003 per question tree generation

### Recommended

* **SSL Certificate**: For secure API communications
* **Object Caching**: Redis or Memcached for improved performance
* **CDN**: For faster frontend script delivery

***

## Installation

### Method 1: Manual Installation

1. **Download Plugin Files**

   ```
   Download the plugin package from your source
   ```
2. **Upload to WordPress**

   ```bash
   # Extract and upload to your WordPress installation
   wp-content/plugins/choicemate/
   ```
3. **Activate Plugin**
   * Navigate to WordPress Admin → Plugins
   * Find "ChoiceMate" and click "Activate"

### Method 2: WordPress Admin Upload

1. **Admin Upload**
   * Go to Plugins → Add New → Upload Plugin
   * Choose the plugin ZIP file
   * Click "Install Now" → "Activate"

### Method 3: WP-CLI Installation

```bash
# Navigate to WordPress root directory
wp plugin install choicemate.zip --activate
```

### Verification

After installation, verify the plugin is active:

* Check for "ChoiceMate" in the WordPress admin menu
* Ensure WooCommerce dependency is met
* Confirm PHP version compatibility

***

## Quick Start Guide

### Step 1: Basic Setup (2 minutes)

1. **Access Plugin Settings**

   ```
   WordPress Admin → ChoiceMate → Settings
   ```
2. **Configure OpenAI API Key**

   ```
   - Get your API key from platform.openai.com/api-keys
   - Paste in "OpenAI API Key" field
   - Click "Test Connection" to verify
   - Save settings
   ```
3. **Configure Basic Options**

   ```
   - Max Recommendations: 5 (recommended)
   - Cache Duration: 1 Hour (cost-effective)
   - Enable Analytics: Yes (recommended)
   ```

### Step 2: Create Your First Question Tree (3 minutes)

1. **Navigate to Question Trees**

   ```
   WordPress Admin → ChoiceMate → Question Trees
   ```
2. **Select Product Category**
   * Choose a category with 10+ products for best results
   * Ensure products have descriptions and attributes
   * Categories with varied products work best
3. **Generate AI Questions**

   ```
   - Click "Generate AI Questions" for selected category
   - Wait 10-30 seconds for AI generation
   - Review generated questions and options
   - Customize questions if needed
   - Click "Save Changes" to activate
   ```

### Step 3: Test Frontend Implementation (1 minute)

1. **Visit Category Page**
   * Go to the WooCommerce category page you configured
   * Look for the ChoiceMate widget at the top of products
2. **Test the Experience**
   * Click "Get Started" to begin the question flow
   * Answer all questions to see recommendations
   * Verify product matches are relevant

### Step 4: Monitor Performance

1. **Check Analytics**

   ```
   WordPress Admin → ChoiceMate → Analytics
   ```
2. **Key Metrics to Monitor**
   * Completion Rate: Aim for >60%
   * Conversion Rate: Track product page visits
   * Popular Answers: Optimize based on patterns

***

## Configuration

### General Settings

#### OpenAI Integration

```php
// Core configuration options
'openai_api_key' => 'sk-...', // Your OpenAI API key
'max_recommendations' => 5,    // Products to show (1-10)
'cache_duration' => 3600,      // Cache in seconds
'auto_generate_trees' => true, // Auto-create for new categories
'enable_analytics' => true,    // Track interactions
```

#### Performance Optimization

```php
// Cache settings for API efficiency
'cache_duration' => [
    3600,   // 1 Hour (recommended for development)
    7200,   // 2 Hours
    14400,  // 4 Hours (recommended for production)
    28800,  // 8 Hours
    86400   // 24 Hours (for high-traffic sites)
]
```

### AI Engine Settings

#### Dynamic Question Generation

The plugin includes advanced AI capabilities that analyze your actual product data:

```php
// Smart dynamic criteria (recommended)
'use_dynamic_criteria' => true,

// Static fallback criteria
'question_criteria' => "
1. Usage/application
2. Budget preferences  
3. Key features/specifications
4. Brand/quality preferences
5. Category-specific criteria
"
```

**Dynamic vs Static Criteria:**

* **Dynamic (Recommended)**: AI analyzes your products and generates smart criteria like "Screen size (13-17 inch available)" for laptops
* **Static**: Uses generic criteria for all categories

### Display & Widget Settings

#### Automatic Display

```php
// Auto-display settings
'auto_display_category_widgets' => true,  // Show on category pages
'auto_display_product_buttons' => true,   // Show alternative finder
```

#### Shortcode Options

For manual placement control:

```php
// Category widget shortcodes
[choicemate_widget category_id="123"]
[choicemate_widget category="Laptops"]

// Alternative finder shortcodes
[choicemate_alternative_finder]
[choicemate_alternative_finder text="Find Better Options" category_id="456"]
```

### Text Customization

All frontend text can be customized:

```php
'text_widget_title' => 'Find Your Perfect Product',
'text_widget_subtitle' => 'Answer a few quick questions to find the best product for you',
'text_start_button' => 'Get Started',
'text_alternative_title' => 'Looking for an alternative?',
'text_alternative_subtitle' => 'Use our AI assistant to find the perfect product for your needs.',
'text_alternative_button' => '🔍 Find Perfect Alternative',
'text_match_reasons_header' => 'Why this product:',
```

***

## Usage

### Creating Question Trees

#### Manual Creation

1. **Category Selection**
   * Choose WooCommerce categories with sufficient product diversity
   * Minimum 5 products recommended, 10+ ideal
   * Ensure products have descriptions and attributes
2. **AI Generation Process**

   ```
   1. Plugin analyzes category products
   2. Extracts attributes, prices, features
   3. Generates contextual questions via OpenAI
   4. Returns 3-5 intelligent questions
   5. Validates and formats response
   ```
3. **Question Types**
   * **Single Choice**: Select one option (most common)
   * **Multiple Choice**: Select multiple options
   * **Range**: Numeric range selection (prices, sizes)

#### Automatic Generation

Enable automatic generation for new categories:

```php
// In settings
'auto_generate_trees' => true,

// Triggers automatically when:
// - New category created with products
// - Existing category gets first products
// - Manual trigger via admin interface
```

### Widget Display

#### Automatic Display Behavior

The widget appears automatically when:

* Category page is viewed
* Category has an active question tree
* Category contains in-stock products
* Auto-display is enabled in settings

#### Manual Placement

Use shortcodes for precise control:

```php
// Basic widget
[choicemate_widget]

// Specific category by ID
[choicemate_widget category_id="123"]

// Specific category by name
[choicemate_widget category="Electronics"]

// Alternative finder on product pages
[choicemate_alternative_finder text="Find Alternatives"]
```

### Customer Experience Flow

1. **Widget Interaction**

   ```
   Customer sees widget → Clicks "Get Started" → Modal opens
   ```
2. **Question Progression**

   ```
   Question 1 → Answer → Question 2 → Answer → ... → Results
   ```
3. **Product Recommendations**

   ```
   AI matches answers → Ranks products → Shows top matches + reasons
   ```
4. **Analytics Tracking**

   ```
   Each interaction logged → Session tracked → Conversions measured
   ```

***

## API Integration

### OpenAI API Integration

#### Request Structure

```javascript
// API request sent to OpenAI
{
    "model": "gpt-3.5-turbo",
    "messages": [{
        "role": "user", 
        "content": "Analyze this product category and generate 3-5 smart questions..."
    }],
    "max_tokens": 1500,
    "temperature": 0.7
}
```

#### Response Processing

```php
// Response validation and parsing
$questions = $this->parse_questions_response($response);
$validated = $this->validate_questions($questions);

// Expected JSON structure
{
    "questions": [
        {
            "question": "What is your primary use case?",
            "type": "single_choice", 
            "options": ["Gaming", "Work", "Study"]
        }
    ]
}
```

### WordPress AJAX Integration

#### Frontend AJAX Calls

```javascript
// Get question tree for category
$.ajax({
    url: choicemate_ai.ajax_url,
    type: 'POST',
    data: {
        action: 'choicemate_get_questions',
        category_id: categoryId,
        nonce: choicemate_ai.nonce
    }
});

// Submit answers and get recommendations  
$.ajax({
    url: choicemate_ai.ajax_url,
    type: 'POST', 
    data: {
        action: 'choicemate_get_recommendations',
        category_id: categoryId,
        answers: JSON.stringify(answers),
        nonce: choicemate_ai.nonce
    }
});
```

#### Backend AJAX Handlers

```php
// Register AJAX endpoints
class Choicemate_Ai_Ajax {
    public function __construct() {
        // Public endpoints (logged in and guest users)
        add_action('wp_ajax_choicemate_get_questions', [$this, 'get_questions']);
        add_action('wp_ajax_nopriv_choicemate_get_questions', [$this, 'get_questions']);
        
        // Admin endpoints (admin users only)
        add_action('wp_ajax_choicemate_generate_tree', [$this, 'generate_tree']);
        add_action('wp_ajax_choicemate_test_ai_connection', [$this, 'test_ai_connection']);
    }
}
```

### Database Integration

#### Question Trees Storage

```sql
-- Question trees table structure
CREATE TABLE wp_choicemate_question_trees (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    category_id bigint(20) NOT NULL,
    category_name varchar(255) NOT NULL,
    tree_data longtext NOT NULL,        -- JSON encoded questions
    version varchar(10) DEFAULT '1.0',
    status enum('draft','active','archived') DEFAULT 'draft',
    created_by bigint(20) NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY category_id (category_id),
    KEY status (status)
);
```

#### Analytics Storage

```sql
-- Analytics table structure  
CREATE TABLE wp_choicemate_analytics (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    session_id varchar(255) NOT NULL,
    category_id bigint(20) NOT NULL,
    question_tree_id mediumint(9) NOT NULL,
    answers longtext NOT NULL,           -- JSON encoded answers
    recommended_products longtext,       -- JSON encoded product IDs
    user_action enum('completed','abandoned','converted') DEFAULT 'abandoned',
    conversion_product_id bigint(20) DEFAULT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY session_id (session_id),
    KEY category_id (category_id),
    KEY question_tree_id (question_tree_id),
    KEY user_action (user_action),
    KEY created_at (created_at)
);
```

***

## Customization

### Frontend Styling

#### CSS Customization

```css
/* Override default widget styles */
.choicemate-widget-container {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 20px;
    margin: 20px 0;
    border-left: 4px solid #667eea;
}

.choicemate-widget-title {
    color: #2d3748;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 8px;
}

.choicemate-start-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.choicemate-start-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
```

#### JavaScript Hooks

```javascript
// Custom event hooks for developers
document.addEventListener('choicemate:widget:opened', function(e) {
    console.log('Widget opened for category:', e.detail.categoryId);
});

document.addEventListener('choicemate:question:answered', function(e) {
    console.log('Question answered:', e.detail);
});

document.addEventListener('choicemate:recommendations:shown', function(e) {
    console.log('Recommendations displayed:', e.detail.products);
});
```

### Backend Hooks & Filters

#### WordPress Hooks

```php
// Modify question generation prompt
add_filter('choicemate_ai_question_prompt', function($prompt, $category, $products) {
    // Customize the AI prompt based on your needs
    return $prompt;
}, 10, 3);

// Filter generated questions before saving
add_filter('choicemate_ai_generated_questions', function($questions, $category_id) {
    // Modify or validate questions
    return $questions;
}, 10, 2);

// Customize product matching algorithm
add_filter('choicemate_product_match_score', function($score, $product, $answers) {
    // Implement custom scoring logic
    return $score;
}, 10, 3);

// Modify recommendation results
add_filter('choicemate_recommendations', function($products, $answers, $category_id) {
    // Filter or reorder recommendations
    return $products;
}, 10, 3);
```

#### Action Hooks

```php
// Before question tree generation
do_action('choicemate_before_generate_tree', $category_id);

// After successful generation
do_action('choicemate_after_generate_tree', $category_id, $questions);

// When customer completes questionnaire
do_action('choicemate_questionnaire_completed', $session_id, $answers, $recommendations);

// When conversion is tracked
do_action('choicemate_conversion_tracked', $session_id, $product_id);
```

### Theme Integration

#### Template Overrides

Create custom templates in your theme:

```php
// In your theme: woocommerce/choicemate/widget.php
<div class="custom-choicemate-widget">
    <h3><?php echo esc_html($widget_title); ?></h3>
    <p><?php echo esc_html($widget_subtitle); ?></p>
    <button class="custom-start-btn" data-category="<?php echo esc_attr($category_id); ?>">
        <?php echo esc_html($start_button_text); ?>
    </button>
</div>
```

#### Hook Integration

```php
// Add widget to custom theme locations
add_action('my_theme_after_hero', function() {
    if (is_product_category()) {
        echo do_shortcode('[choicemate_widget]');
    }
});

// Custom widget trigger
add_action('woocommerce_before_single_product_summary', function() {
    echo do_shortcode('[choicemate_alternative_finder text="Find Similar Products"]');
}, 15);
```

***

## Analytics

### Analytics Dashboard

Access comprehensive analytics via:

```
WordPress Admin → ChoiceMate → Analytics
```

#### Key Metrics

1. **Engagement Metrics**
   * Widget impression count
   * Start rate (impressions → starts)
   * Completion rate (starts → completions)
   * Average time to complete
2. **Conversion Metrics**
   * Recommendation clicks
   * Product page visits from recommendations
   * Purchase conversions
   * Revenue attributed to ChoiceMate
3. **Question Performance**
   * Most common answers per question
   * Questions causing abandonment
   * Answer distribution analysis
   * Question effectiveness scores
4. **Product Performance**
   * Most recommended products
   * Highest converting recommendations
   * Products never recommended (optimization opportunity)
   * Recommendation accuracy feedback

### Data Export

#### Export Options

```php
// Export analytics data
$analytics = new Choicemate_Ai_Analytics();

// Get data for specific date range
$data = $analytics->get_analytics_data([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-31',
    'category_id' => 123,
    'format' => 'csv' // or 'json'
]);

// Export formats available
'csv'  => 'CSV file download',
'json' => 'JSON data export', 
'pdf'  => 'PDF report generation'
```

#### Custom Analytics Queries

```php
// Custom analytics queries
global $wpdb;

// Completion rate by category
$completion_rates = $wpdb->get_results("
    SELECT 
        category_id,
        category_name,
        COUNT(*) as total_sessions,
        SUM(CASE WHEN user_action = 'completed' THEN 1 ELSE 0 END) as completed,
        ROUND(SUM(CASE WHEN user_action = 'completed' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) as completion_rate
    FROM {$wpdb->prefix}choicemate_analytics
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY category_id, category_name
    ORDER BY completion_rate DESC
");

// Popular answer combinations
$popular_answers = $wpdb->get_results("
    SELECT 
        answers,
        COUNT(*) as frequency,
        AVG(CASE WHEN user_action = 'converted' THEN 1 ELSE 0 END) as conversion_rate
    FROM {$wpdb->prefix}choicemate_analytics  
    WHERE user_action IN ('completed', 'converted')
    GROUP BY answers
    HAVING frequency >= 5
    ORDER BY frequency DESC
");
```

### Privacy & GDPR Compliance

#### Data Storage

* All analytics data stored locally in WordPress database
* No personal identifiable information sent to external services
* Session IDs are anonymized and not linked to user accounts
* Data retention settings configurable

#### GDPR Features

```php
// GDPR compliance features
'enable_cookie_consent' => true,        // Respect cookie consent
'anonymize_ip_addresses' => true,       // Hash IP addresses  
'data_retention_days' => 365,           // Auto-delete old data
'allow_data_export' => true,            // User data export
'allow_data_deletion' => true,          // User data deletion
```

***

## Troubleshooting

### Common Issues & Solutions

#### 1. Widget Not Displaying

**Symptoms:**

* Widget doesn't appear on category pages
* No ChoiceMate element visible

**Diagnosis:**

```php
// Check category has active question tree
global $wpdb;
$has_tree = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}choicemate_question_trees 
     WHERE category_id = %d AND status = 'active'",
    $category_id
));

// Check category has products
$product_count = wc_get_products([
    'category' => [$category_id],
    'stock_status' => 'instock',
    'limit' => 1,
    'return' => 'ids'
]);
```

**Solutions:**

1. Create question tree for the category
2. Ensure category has in-stock products
3. Check auto-display settings are enabled
4. Verify theme compatibility with WooCommerce hooks

#### 2. OpenAI API Errors

**Common Error Messages:**

```
"OpenAI API key not configured"
"OpenAI API error: 401 Unauthorized" 
"OpenAI API error: 429 Too Many Requests"
"Invalid JSON response from OpenAI"
```

**Solutions:**

```php
// Test API connection
$openai = new Choicemate_Ai_OpenAI();
$test = $openai->test_connection();

if (is_wp_error($test)) {
    // Handle specific errors
    switch ($test->get_error_code()) {
        case 'no_api_key':
            // Add API key in settings
            break;
        case 'api_error':
            // Check API key validity and billing
            break;
        case 'json_error':  
            // Check OpenAI service status
            break;
    }
}
```

#### 3. Poor Question Quality

**Symptoms:**

* Generic or irrelevant questions generated
* Questions don't match product category
* Too few or too many questions

**Diagnosis:**

```php
// Analyze product data quality
$products = $this->get_category_products($category_id, 20);
$analysis = $this->analyze_products($products);

// Check for:
echo "Product count: " . count($products) . "\n";
echo "Price range: €{$analysis['price_range']['min']} - €{$analysis['price_range']['max']}\n";  
echo "Attributes found: " . count($analysis['common_attributes']) . "\n";
echo "Common features: " . implode(', ', array_keys($analysis['features'])) . "\n";
```

**Solutions:**

1. **Improve Product Data:**
   * Add detailed product descriptions
   * Use WooCommerce attributes consistently
   * Ensure varied product selection in category
2. **Customize AI Prompts:**

   ```php
   add_filter('choicemate_ai_question_prompt', function($prompt, $category, $products) {
       // Add category-specific context
       if (strpos($category->name, 'Electronics') !== false) {
           $prompt .= "\nFocus on technical specifications and usage scenarios.";
       }
       return $prompt;
   }, 10, 3);
   ```

#### 4. Performance Issues

**Symptoms:**

* Slow widget loading
* High API costs
* Server timeouts

**Optimization Solutions:**

```php
// Increase cache duration
'cache_duration' => 14400, // 4 hours

// Reduce API calls
'auto_generate_trees' => false, // Manual generation only

// Optimize database
wp_optimize_database_tables(['choicemate_analytics']);

// Enable object caching
wp_cache_set($cache_key, $data, 'choicemate', 3600);
```

#### 5. JavaScript Errors

**Common Console Errors:**

```javascript
"Uncaught ReferenceError: React is not defined"
"choicemate_ai is not defined"
"AJAX request failed"
```

**Solutions:**

1. **Script Dependencies:**

   ```php
   // Check script loading order
   wp_enqueue_script('choicemate-public', $url, [
       'jquery', 'react', 'react-dom', 'babel-standalone'
   ], $version, true);
   ```
2. **AJAX Configuration:**

   ```php
   // Verify AJAX localization
   wp_localize_script('choicemate-public', 'choicemate_ai', [
       'ajax_url' => admin_url('admin-ajax.php'),
       'nonce' => wp_create_nonce('choicemate_ai_public_nonce')
   ]);
   ```

### Debug Mode

#### Enable Debug Logging

```php
// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('CHOICEMATE_AI_DEBUG', true);

// View logs
tail -f wp-content/debug.log | grep "ChoiceMate"
```

#### Debug Information

```php
// Get debug information
$debug_info = [
    'plugin_version' => CHOICEMATE_AI_VERSION,
    'wordpress_version' => get_bloginfo('version'),
    'woocommerce_version' => WC()->version,
    'php_version' => phpversion(),
    'database_tables' => Choicemate_Ai_Database::check_tables(),
    'api_key_configured' => !empty(get_option('choicemate_ai_settings')['openai_api_key']),
    'active_trees' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}choicemate_question_trees WHERE status = 'active'"),
];
```

***

## API Reference

### REST API Endpoints

#### Public Endpoints

**Get Category Questions**

```http
POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=choicemate_get_questions&category_id=123&nonce=abc123
```

Response:

```json
{
    "success": true,
    "data": {
        "questions": [
            {
                "id": 1,
                "question": "What is your primary use case?",
                "type": "single_choice",
                "options": ["Gaming", "Work", "Study"]
            }
        ],
        "category_name": "Laptops"
    }
}
```

**Submit Answers & Get Recommendations**

```http
POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=choicemate_get_recommendations&category_id=123&answers={"1":"Gaming"}&nonce=abc123
```

Response:

```json
{
    "success": true,
    "data": {
        "products": [
            {
                "id": 456,
                "name": "Gaming Laptop Pro",
                "price": "€1299.00", 
                "url": "/product/gaming-laptop-pro/",
                "image": "/wp-content/uploads/laptop.jpg",
                "match_score": 95,
                "reasons": [
                    "Perfect for gaming with high-end GPU",
                    "Matches your budget requirements"
                ]
            }
        ],
        "session_id": "sess_abc123"
    }
}
```

#### Admin Endpoints

**Generate Question Tree**

```http
POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=choicemate_generate_tree&category_id=123&nonce=abc123
```

**Test API Connection**

```http
POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=choicemate_test_ai_connection&nonce=abc123
```

**Save Settings**

```http
POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=choicemate_save_settings&openai_api_key=sk-...&max_recommendations=5&nonce=abc123
```

### PHP API Classes

#### Main Classes

**Choicemate\_Ai\_OpenAI**

```php
// Generate questions for category
$openai = new Choicemate_Ai_OpenAI();
$questions = $openai->generate_questions_for_category($category_id);

// Test API connection
$status = $openai->test_connection();
```

**Choicemate\_Ai\_Product\_Matcher**

```php
// Match products to answers
$matcher = new Choicemate_Ai_Product_Matcher();
$recommendations = $matcher->find_matching_products($category_id, $answers);
```

**Choicemate\_Ai\_Database**

```php
// Database operations
$db = new Choicemate_Ai_Database();

// Create/repair tables
$result = $db->create_tables();
$check = $db->check_tables();
$repair = $db->repair_tables();
```

#### Helper Functions

```php
// Check if category has question tree
function choicemate_category_has_tree($category_id) {
    global $wpdb;
    return (bool) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}choicemate_question_trees 
         WHERE category_id = %d AND status = 'active'",
        $category_id
    ));
}

// Get category question tree
function choicemate_get_category_tree($category_id) {
    global $wpdb;
    return $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}choicemate_question_trees 
         WHERE category_id = %d AND status = 'active' 
         ORDER BY created_at DESC LIMIT 1",
        $category_id
    ));
}

// Track analytics event
function choicemate_track_event($session_id, $event_type, $data = []) {
    // Implementation for tracking custom events
}
```

***

## Developer Guide

### Plugin Architecture

#### File Structure

```
choicemate/
├── choicemate-ai.php              # Main plugin file
├── includes/                      # Core functionality
│   ├── class-choicemate-ai.php           # Main plugin class
│   ├── class-choicemate-ai-loader.php    # Hook loader
│   ├── class-choicemate-ai-ajax.php      # AJAX handlers
│   ├── class-choicemate-ai-database.php  # Database operations
│   └── api/                              # API integrations
│       ├── class-choicemate-ai-openai.php        # OpenAI client
│       └── class-choicemate-ai-product-matcher.php # Product matching
├── admin/                         # Admin interface
│   ├── class-choicemate-ai-admin.php     # Admin functionality
│   ├── js/choicemate-ai-admin.js         # Admin React components
│   ├── css/choicemate-ai-admin.css       # Admin styling
│   └── views/                            # Admin templates
│       ├── admin-display.php
│       ├── settings-display.php
│       ├── trees-display.php
│       └── analytics-display.php
├── public/                        # Frontend functionality
│   ├── class-choicemate-ai-public.php    # Public functionality
│   ├── js/choicemate-ai-public.js        # Frontend React components
│   ├── css/choicemate-ai-public.css      # Frontend styling
│   └── templates/                        # Frontend templates
│       └── choice-widget.php
└── languages/                     # Translation files
    └── choicemate-ai.pot
```

#### Core Classes

**Main Plugin Class (Choicemate\_Ai)**

```php
class Choicemate_Ai {
    protected $loader;
    protected $plugin_name;
    protected $version;

    public function __construct() {
        $this->load_dependencies();
        $this->set_locale();
        $this->define_admin_hooks();
        $this->define_public_hooks();
    }

    public function run() {
        $this->loader->run();
    }
}
```

**Loader System (Choicemate\_Ai\_Loader)**

```php
class Choicemate_Ai_Loader {
    protected $actions = [];
    protected $filters = [];

    public function add_action($hook, $component, $callback, $priority = 10, $accepted_args = 1) {
        $this->actions = $this->add($this->actions, $hook, $component, $callback, $priority, $accepted_args);
    }

    public function run() {
        foreach ($this->filters as $hook) {
            add_filter($hook['hook'], [$hook['component'], $hook['callback']], $hook['priority'], $hook['accepted_args']);
        }
        
        foreach ($this->actions as $hook) {
            add_action($hook['hook'], [$hook['component'], $hook['callback']], $hook['priority'], $hook['accepted_args']);
        }
    }
}
```

### Custom Development

#### Creating Extensions

**Plugin Extension Structure**

```php
<?php
/*
Plugin Name: ChoiceMate Extension - Custom Features
Description: Custom features for ChoiceMate
Version: 1.0.0
*/

class ChoiceMate_Custom_Extension {
    public function __construct() {
        add_action('plugins_loaded', [$this, 'init']);
    }

    public function init() {
        // Ensure ChoiceMate is active
        if (!class_exists('Choicemate_Ai')) {
            return;
        }

        $this->add_custom_hooks();
    }

    private function add_custom_hooks() {
        // Custom question generation
        add_filter('choicemate_ai_question_prompt', [$this, 'custom_prompt'], 10, 3);
        
        // Custom product matching
        add_filter('choicemate_product_match_score', [$this, 'custom_scoring'], 10, 3);
        
        // Custom analytics
        add_action('choicemate_questionnaire_completed', [$this, 'track_custom_event'], 10, 3);
    }

    public function custom_prompt($prompt, $category, $products) {
        // Add industry-specific context
        if ($this->is_fashion_category($category)) {
            $prompt .= "\nFocus on style, fit, and seasonal preferences for fashion items.";
        }
        return $prompt;
    }

    public function custom_scoring($score, $product, $answers) {
        // Implement custom scoring algorithm
        $custom_score = $this->calculate_custom_match($product, $answers);
        return ($score + $custom_score) / 2;
    }
}

new ChoiceMate_Custom_Extension();
```

#### Custom Question Types

```php
// Add custom question type
add_filter('choicemate_question_types', function($types) {
    $types['slider'] = [
        'label' => 'Slider Range',
        'validation' => 'numeric',
        'frontend_component' => 'SliderQuestion'
    ];
    return $types;
});

// Handle custom question in frontend
add_action('choicemate_render_question_slider', function($question) {
    ?>
    <div class="choicemate-slider-question">
        <label><?php echo esc_html($question['question']); ?></label>
        <input type="range" 
               min="<?php echo esc_attr($question['min']); ?>"
               max="<?php echo esc_attr($question['max']); ?>"
               value="<?php echo esc_attr($question['default']); ?>"
               data-question-id="<?php echo esc_attr($question['id']); ?>">
    </div>
    <?php
});
```

#### Custom Analytics

```php
// Track custom conversion events
class ChoiceMate_Custom_Analytics {
    public function __construct() {
        add_action('woocommerce_thankyou', [$this, 'track_conversion']);
    }

    public function track_conversion($order_id) {
        // Check if customer came from ChoiceMate
        $session_id = WC()->session->get('choicemate_session_id');
        if (!$session_id) return;

        $order = wc_get_order($order_id);
        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            
            // Update analytics with conversion
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'choicemate_analytics',
                [
                    'user_action' => 'converted',
                    'conversion_product_id' => $product_id
                ],
                ['session_id' => $session_id],
                ['%s', '%d'],
                ['%s']
            );
        }
    }
}
new ChoiceMate_Custom_Analytics();
```

### Testing & Development

#### Unit Testing Setup

```php
// tests/TestChoiceMateOpenAI.php
class TestChoiceMateOpenAI extends WP_UnitTestCase {
    private $openai;

    public function setUp() {
        parent::setUp();
        $this->openai = new Choicemate_Ai_OpenAI();
    }

    public function test_question_generation() {
        $category_id = $this->create_test_category();
        $questions = $this->openai->generate_questions_for_category($category_id);
        
        $this->assertFalse(is_wp_error($questions));
        $this->assertGreaterThan(2, count($questions));
        $this->assertArrayHasKey('question', $questions[0]);
    }

    private function create_test_category() {
        return wp_insert_term('Test Category', 'product_cat')['term_id'];
    }
}
```

#### Development Environment

```bash
# Install development dependencies
composer install --dev

# Run PHP CodeSniffer
composer phpcs

# Run PHPUnit tests  
composer test

# Watch for file changes during development
npm run watch
```

***

## FAQ

### General Questions

**Q: What makes ChoiceMate different from other product recommendation plugins?** A: ChoiceMate uses AI to automatically generate intelligent, category-specific questions by analyzing your actual product data. Instead of generic questionnaires, it creates contextual questions like "Screen size (13-17 inch available)" for laptops or "Activity level (Beginner/Intermediate/Professional)" for sports equipment.

**Q: Do I need technical knowledge to use ChoiceMate?** A: No technical knowledge required. The plugin works out-of-the-box with automatic question generation. Simply install, add your OpenAI API key, and the plugin handles the rest.

**Q: How much does it cost to run ChoiceMate?** A: The plugin itself is a one-time purchase. You'll need an OpenAI API key which typically costs $0.001-0.003 per question tree generation. Most small to medium stores spend less than $5/month on API costs.

### Installation & Setup

**Q: Can I use ChoiceMate without OpenAI?** A: No, OpenAI is required for the AI question generation. However, you can manually create question trees and use the recommendation engine without ongoing API costs.

**Q: Does ChoiceMate work with my theme?** A: ChoiceMate is designed to work with any properly coded WordPress theme that supports WooCommerce. It uses standard WooCommerce hooks and provides shortcodes for manual placement if needed.

**Q: What happens if I switch themes?** A: Your question trees and analytics data remain intact. The widget display may need minor adjustment depending on your new theme's structure, but all functionality continues working.

### Functionality

**Q: How does the AI generate relevant questions?** A: The AI analyzes your product catalog including prices, attributes, descriptions, and features. It then creates contextual questions that help differentiate between your actual products, ensuring relevant recommendations.

**Q: Can customers skip questions?** A: The current version requires all questions to be answered for accurate recommendations. This ensures the best possible product matches for your customers.

**Q: How accurate are the recommendations?** A: Recommendation accuracy depends on your product data quality. With detailed descriptions and attributes, accuracy typically ranges from 85-95%. The plugin learns and improves over time based on customer interactions.

**Q: Can I customize the generated questions?** A: Yes, after AI generation, you can edit, add, or remove questions and answer options. You have full control over the final questionnaire your customers see.

### Performance & Analytics

**Q: Will ChoiceMate slow down my website?** A: ChoiceMate is optimized for performance with caching, lazy loading, and efficient database queries. The frontend React components load asynchronously and don't impact your site's core performance.

**Q: What analytics data can I see?** A: ChoiceMate tracks completion rates, popular answers, conversion rates, recommended products performance, and customer journey analytics. All data is stored locally and GDPR compliant.

**Q: How do I interpret the analytics?** A: Focus on completion rates (aim for >60%), conversion rates from recommendations, and popular answer patterns. Use this data to optimize your product catalog and question effectiveness.

### Troubleshooting

**Q: The widget isn't showing on my category pages.** A: Check that: 1) The category has an active question tree, 2) The category contains in-stock products, 3) Auto-display is enabled in settings, 4) Your theme properly implements WooCommerce hooks.

**Q: I'm getting "API key not configured" errors.** A: Go to ChoiceMate → Settings and add your OpenAI API key. Get one from platform.openai.com/api-keys. Click "Test Connection" to verify it's working.

**Q: The generated questions seem irrelevant.** A: This usually happens when products lack detailed descriptions or attributes. Improve your product data with comprehensive descriptions, proper categorization, and WooCommerce attributes.

**Q: Can I use ChoiceMate in multiple languages?** A: ChoiceMate automatically detects Dutch and English. The AI generates questions in the appropriate language. Full multilingual support is planned for future versions.

### Advanced Usage

**Q: Can I integrate ChoiceMate with my existing recommendation system?** A: Yes, ChoiceMate provides hooks and filters for custom integration. You can modify the recommendation algorithm, add custom scoring, or integrate with third-party systems.

**Q: How do I backup my question trees?** A: Question trees are stored in your WordPress database. Regular database backups will preserve all ChoiceMate data. You can also export specific question trees from the admin interface.

**Q: Can I A/B test different question approaches?** A: While built-in A/B testing isn't included, you can create multiple question trees for the same category and manually switch between them to test different approaches.

**Q: Is there an API for developers?** A: Yes, ChoiceMate provides REST API endpoints and WordPress hooks for custom development. See the Developer Guide section for complete API documentation.

***

## Support

### Getting Help

#### Documentation Resources

* **Installation Guide**: Step-by-step setup instructions
* **Quick Start Guide**: Get running in 5 minutes
* **Video Tutorials**: Visual walkthroughs of key features
* **Developer Documentation**: Technical integration guides

#### Community Support

* **WordPress Plugin Directory**: Community reviews and basic support
* **GitHub Issues**: Bug reports and feature requests
* **Community Forum**: User discussions and tips

#### Priority Support

* **Email Support**: Direct assistance from our team
* **Live Chat**: Real-time help during business hours
* **Custom Development**: Tailored solutions for enterprise needs

### Contact Information

**General Support**

* Email: <info@velocityplugins.com>
* Response Time: 24-48 hours
* Available: Monday-Friday, 9 AM - 5 PM CET

**Technical Support**

* Email: <technical@velocityplugins.com>
* For: API integration, custom development, advanced troubleshooting
* Response Time: 12-24 hours for priority customers

**Sales & Licensing**

* Email: <sales@velocityplugins.com>
* For: Licensing questions, bulk purchases, enterprise features

### Bug Reports & Feature Requests

#### Bug Reports

When reporting bugs, please include:

```
**Bug Description:**
Brief description of the issue

**Steps to Reproduce:**
1. Go to...
2. Click on...
3. See error

**Expected Behavior:**
What should happen

**Actual Behavior:**
What actually happens

**Environment:**
- WordPress version: 
- WooCommerce version:
- ChoiceMate version:
- PHP version:
- Browser:

**Error Messages:**
Any console errors or PHP errors

**Screenshots:**
If applicable
```

#### Feature Requests

Submit feature requests with:

* **Use Case**: Why you need this feature
* **Description**: What the feature should do
* **Priority**: How important is this to your business
* **Alternatives**: Current workarounds you're using

### Frequently Requested Features

#### Planned Features (Roadmap)

* **Multi-language Support**: Full i18n for all languages
* **Advanced Analytics**: Conversion funnel analysis, cohort reports
* **A/B Testing**: Built-in split testing for question approaches
* **Machine Learning**: Improve recommendations based on customer behavior
* **Visual Question Builder**: Drag-and-drop question creation interface
* **Integration APIs**: Connect with CRM, email marketing, and analytics platforms

#### Under Consideration

* **Voice Interface**: Audio questions and responses
* **Mobile App**: Native mobile application for question management
* **White-label Solution**: Rebrandable version for agencies
* **Advanced Pricing**: Dynamic pricing based on answers

### Community Contributions

#### Contributing to ChoiceMate

**Code Contributions:**

* Fork the repository on GitHub
* Create feature branches for new functionality
* Follow WordPress coding standards
* Include unit tests for new features
* Submit pull requests for review

**Translation Contributions:**

* Help translate ChoiceMate into your language
* Join our translation team
* Use standard WordPress translation tools (Poedit, GlotPress)

**Documentation Contributions:**

* Improve existing documentation
* Create tutorials and guides
* Share use cases and success stories

#### Community Guidelines

* **Be Respectful**: Treat all community members with respect
* **Stay On Topic**: Keep discussions relevant to ChoiceMate
* **Share Knowledge**: Help other users when possible
* **Provide Feedback**: Help us improve the plugin

***

### Version History & Updates

#### Current Version: 1.0.0

**Release Date:** January 2025

**Features:**

* AI-powered question generation with OpenAI GPT-3.5-turbo
* Smart dynamic criteria based on product analysis
* React-based frontend widgets and modals
* Comprehensive analytics and conversion tracking
* WordPress admin interface with tabbed settings
* Shortcode support for flexible placement
* HPOS compatibility for WooCommerce
* Multi-language support (Dutch/English)

#### Automatic Updates

* Updates delivered through WordPress plugin system
* Automatic security patches
* Feature updates with backward compatibility
* Database migration handling for schema changes

#### Support Lifecycle

* **Current Version**: Full support and regular updates
* **Previous Version**: Security updates only
* **Legacy Versions**: Community support via forums

***

**Thank you for choosing ChoiceMate! We're committed to helping you create exceptional shopping experiences for your customers.**

For the latest updates and announcements, visit: <https://velocityplugins.com/plugins/choicemate>
