# A1AI Database Structure

## Overview

The A1AI plugin uses a structured database design to store chatbot configurations, conversations, messages, and AI-specific data. This document outlines the database schema and relationships.

## Database Tables

### Core Tables

#### `wp_a1ai_chatbots`
Stores basic chatbot information and general settings.

```sql
CREATE TABLE wp_a1ai_chatbots (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    name varchar(255) NOT NULL,
    settings longtext NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
    updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (id)
);
```

**Fields:**
- `id` - Unique chatbot identifier
- `name` - Display name for the chatbot
- `settings` - JSON-encoded general settings (appearance, positioning, etc.)
- `created_at` - Creation timestamp
- `updated_at` - Last update timestamp

#### `wp_a1ai_conversations`
Tracks chat sessions between users and chatbots.

```sql
CREATE TABLE wp_a1ai_conversations (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    chatbot_id mediumint(9) NOT NULL,
    user_id bigint(20) DEFAULT 0 NOT NULL,
    session_id varchar(255) NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (id),
    KEY chatbot_id (chatbot_id),
    KEY user_id (user_id),
    KEY session_id (session_id)
);
```

**Fields:**
- `id` - Unique conversation identifier
- `chatbot_id` - Reference to the chatbot
- `user_id` - WordPress user ID (0 for anonymous users)
- `session_id` - Unique session identifier
- `created_at` - Conversation start timestamp

#### `wp_a1ai_messages`
Stores individual messages within conversations.

```sql
CREATE TABLE wp_a1ai_messages (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    conversation_id mediumint(9) NOT NULL,
    role varchar(50) NOT NULL,
    content longtext NOT NULL,
    tokens_used int DEFAULT 0 NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (id),
    KEY conversation_id (conversation_id)
);
```

**Fields:**
- `id` - Unique message identifier
- `conversation_id` - Reference to the conversation
- `role` - Message role ('user', 'assistant', 'system')
- `content` - Message content
- `tokens_used` - Token count for AI responses
- `created_at` - Message timestamp

#### `wp_a1ai_adjustments`
Stores manual adjustments to AI responses for training/improvement.

```sql
CREATE TABLE wp_a1ai_adjustments (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    chatbot_id mediumint(9) NOT NULL,
    session_id varchar(255) NOT NULL,
    user_message text NOT NULL,
    ai_message text NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (id),
    KEY chatbot_id (chatbot_id)
);
```

**Fields:**
- `id` - Unique adjustment identifier
- `chatbot_id` - Reference to the chatbot
- `session_id` - Session where adjustment was made
- `user_message` - Original user message
- `ai_message` - AI response that was adjusted
- `created_at` - Adjustment timestamp

### AI Configuration Tables

#### `wp_a1ai_system_prompts`
Dedicated table for storing system prompts that define AI behavior.

```sql
CREATE TABLE wp_a1ai_system_prompts (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    chatbot_id mediumint(9) NOT NULL,
    prompt_name varchar(255) NOT NULL,
    prompt_content longtext NOT NULL,
    is_active tinyint(1) NOT NULL DEFAULT 1,
    created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY chatbot_id (chatbot_id)
);
```

**Fields:**
- `id` - Unique prompt identifier
- `chatbot_id` - Reference to the chatbot
- `prompt_name` - Human-readable name for the prompt
- `prompt_content` - The actual system prompt content
- `is_active` - Whether this prompt is currently active (1/0)
- `created_at` - Creation timestamp
- `updated_at` - Last update timestamp

**Usage:**
- Only one system prompt can be active per chatbot at a time
- When a new prompt is saved, previous prompts are deactivated
- System prompts define the AI's role, personality, and behavior

#### `wp_a1ai_custom_instructions`
Dedicated table for storing custom instructions that guide AI responses.

```sql
CREATE TABLE wp_a1ai_custom_instructions (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    chatbot_id mediumint(9) NOT NULL,
    instruction_name varchar(255) NOT NULL,
    instruction_content longtext NOT NULL,
    instruction_type varchar(50) NOT NULL DEFAULT 'general',
    priority int(11) NOT NULL DEFAULT 0,
    is_active tinyint(1) NOT NULL DEFAULT 1,
    created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY chatbot_id (chatbot_id)
);
```

**Fields:**
- `id` - Unique instruction identifier
- `chatbot_id` - Reference to the chatbot
- `instruction_name` - Human-readable name for the instruction
- `instruction_content` - The actual instruction content
- `instruction_type` - Category of instruction ('general', 'product', 'support', etc.)
- `priority` - Order of importance (lower numbers = higher priority)
- `is_active` - Whether this instruction is currently active (1/0)
- `created_at` - Creation timestamp
- `updated_at` - Last update timestamp

**Usage:**
- Multiple custom instructions can be active per chatbot
- Instructions are ordered by priority
- Different instruction types allow for categorization
- Instructions provide context, knowledge, and constraints

## Relationships

```
wp_a1ai_chatbots (1) ←→ (many) wp_a1ai_conversations
wp_a1ai_chatbots (1) ←→ (many) wp_a1ai_system_prompts
wp_a1ai_chatbots (1) ←→ (many) wp_a1ai_custom_instructions
wp_a1ai_chatbots (1) ←→ (many) wp_a1ai_adjustments

wp_a1ai_conversations (1) ←→ (many) wp_a1ai_messages
```

## Benefits of Dedicated Tables

### 1. **Better Performance**
- Direct queries on system prompts and custom instructions
- No need to parse JSON for AI configuration data
- Efficient indexing on specific fields

### 2. **Improved Data Management**
- Version control for system prompts and instructions
- Easy backup and restore of AI configurations
- Better data integrity and validation

### 3. **Enhanced Functionality**
- Multiple custom instructions per chatbot
- Priority-based instruction ordering
- Categorization of instructions by type
- Historical tracking of AI configurations

### 4. **Scalability**
- Support for complex AI configurations
- Easy addition of new instruction types
- Better support for advanced features

## Migration from JSON Storage

The plugin includes a migration system that automatically:

1. **Creates new tables** during plugin activation
2. **Migrates existing data** from JSON settings to dedicated tables
3. **Maintains backward compatibility** during transition
4. **Provides rollback functionality** if needed

### Migration Process

1. **Detection**: Plugin checks current database version
2. **Table Creation**: New tables are created if they don't exist
3. **Data Migration**: Existing `system_prompt` and `custom_instructions` from JSON settings are moved to dedicated tables
4. **Version Update**: Database version is updated to reflect new schema

### Rollback Support

If issues arise, the migration can be rolled back:
- Tables are dropped
- Database version is reverted
- Original JSON storage continues to work

## Usage Examples

### Getting System Prompt
```php
$data_manager = new A1AI_Data_Manager();
$system_prompt = $data_manager->get_system_prompt($chatbot_id);
```

### Saving System Prompt
```php
$data_manager = new A1AI_Data_Manager();
$prompt_id = $data_manager->save_system_prompt(
    $chatbot_id,
    'Customer Support Bot',
    'You are a helpful customer support assistant...'
);
```

### Getting Custom Instructions
```php
$data_manager = new A1AI_Data_Manager();
$instructions = $data_manager->get_custom_instructions($chatbot_id, 'product');
```

### Saving Custom Instruction
```php
$data_manager = new A1AI_Data_Manager();
$instruction_id = $data_manager->save_custom_instruction(
    $chatbot_id,
    'Product Knowledge',
    'Our products include...',
    'product',
    1
);
```

## Best Practices

### 1. **System Prompts**
- Keep prompts concise and focused
- Use clear, specific language
- Test prompts thoroughly before deployment
- Version control important prompt changes

### 2. **Custom Instructions**
- Use descriptive names for easy identification
- Categorize instructions by type
- Set appropriate priorities
- Keep instructions up to date

### 3. **Performance**
- Use the dedicated methods in `A1AI_Data_Manager`
- Cache frequently accessed data
- Monitor query performance
- Regular database maintenance

### 4. **Data Integrity**
- Always use the provided sanitization methods
- Validate data before storage
- Use transactions for complex operations
- Regular backups of AI configurations

## Future Enhancements

The dedicated table structure enables future features such as:

- **A/B Testing**: Compare different system prompts
- **Instruction Templates**: Reusable instruction sets
- **Advanced Analytics**: Track instruction effectiveness
- **Multi-language Support**: Language-specific instructions
- **Conditional Instructions**: Context-aware instruction application 