# Changelog

## July 19, 2025 - Side-by-Side Conversation Preview

**Prompt**: "We need a way to view the chats, when we click the view button. make it so when the view button is clicked it opens a preview to the right of the table area"

**Files Modified**:

1. `admin/partials/a1ai-admin-conversations.php` - Redesigned layout:
   - Replaced modal with side-by-side layout
   - Added conversation preview panel to the right of the table
   - Added conversation metadata display (chatbot, user, time, stats)
   - Added placeholder state when no conversation is selected
   - Added data attributes to table rows for selection

2. `admin/css/a1ai-admin.css` - Added side-by-side styling:
   - Flexbox layout for conversations container
   - Fixed height layout with proper overflow handling
   - Preview panel styling with header, info section, and messages area
   - Row selection highlighting with hover and selected states
   - Responsive design for mobile devices (stacks vertically)

3. `admin/js/a1ai-admin.js` - Updated interaction logic:
   - Replaced modal functionality with preview panel
   - Added row click functionality for easier selection
   - Updated conversation display to show in preview panel
   - Added conversation metadata display (chatbot name, user, timestamps, stats)
   - Added preview close functionality
   - Prevented event bubbling for action buttons

4. `admin/class-a1ai-admin.php` - Enhanced conversation data:
   - Added chatbot name to conversation response
   - Added user display name to conversation response
   - Improved data structure for preview panel

**New Features**:
- **Side-by-Side Layout**: Table on left, preview panel on right
- **Row Selection**: Click any row to view conversation details
- **Conversation Metadata**: Shows chatbot name, user, start time, message count, and token usage
- **Preview Panel**: Dedicated area for viewing conversation details
- **Responsive Design**: Stacks vertically on mobile devices
- **Visual Feedback**: Selected row highlighting and hover states

**User Experience Improvements**:
- **Faster Navigation**: No modal popup, instant preview
- **Better Context**: Always see the table while viewing conversations
- **Easier Selection**: Click anywhere on a row to view details
- **More Information**: See conversation metadata at a glance
- **Mobile Friendly**: Responsive layout works on all devices

## July 19, 2025 - Tabbed Chatbots Page with Conversations

**Prompt**: "Within Chatbots We need tabbed pages like we have on settings or within the chatbots when we are editing them. The first tabbed page should be the current Manage Chatbots page, and then add a Conversations tab"

**Files Modified**:

1. `admin/partials/a1ai-admin-chatbots.php` - Added tabbed interface:
   - Added tab navigation with "Manage Chatbots" and "Conversations" tabs
   - Wrapped existing chatbot list in first tab
   - Included conversations partial in second tab

2. `admin/partials/a1ai-admin-conversations.php` - New conversations tab:
   - Created new partial for conversations management
   - Shows recent conversations in a table format
   - Displays chatbot name, user, session ID, message count, tokens used, and timestamps
   - Includes View and Delete actions for each conversation
   - Added modal for viewing conversation details

3. `includes/class-a1ai-data-manager.php` - Added conversation retrieval:
   - Added `get_recent_conversations()` method to fetch recent conversations
   - Supports limit parameter for pagination

4. `admin/css/a1ai-admin.css` - Added modal and conversation styles:
   - Modal overlay and content styling
   - Conversation message styling with role-based colors
   - Responsive design for mobile devices
   - User, assistant, and system message styling

5. `admin/js/a1ai-admin.js` - Added conversation functionality:
   - View conversation modal functionality
   - Delete conversation with confirmation
   - Modal close and outside click handling
   - AJAX calls for conversation management

6. `admin/class-a1ai-admin.php` - Added AJAX handlers:
   - `get_conversation()` method for fetching conversation details
   - `delete_conversation()` method for removing conversations
   - Proper nonce verification and capability checks
   - Foreign key constraint handling for message deletion

**New Features**:
- **Tabbed Interface**: Chatbots page now has tabs like Settings page
- **Conversations Tab**: View and manage recent conversations
- **Conversation Details**: Modal popup to view full conversation history
- **Conversation Management**: Delete individual conversations
- **Token Tracking**: Shows token usage per conversation
- **User Information**: Displays user names or "Guest" for anonymous users
- **Responsive Design**: Works on mobile and desktop devices

**User Experience**:
- Clean tabbed navigation between chatbot management and conversation monitoring
- Easy access to conversation history for debugging and analysis
- Visual distinction between user, assistant, and system messages
- Confirmation dialogs for destructive actions
- Real-time updates without page reload

## July 19, 2025 - Token Usage Tracking Fix

**Prompt**: "On the dashboard, Total Tokens Used is not tracking, it just says 0"

**Files Modified**:

1. `public/class-a1ai-public.php` - Fixed token tracking:
   - Modified `handle_send_message()` to capture token usage from AI response
   - Updated `process_ai_message()` to return both message and token usage
   - Now passes token count when storing AI messages with `add_message()`

2. `includes/class-a1ai-openai.php` - Simplified token handling:
   - Removed redundant `update_message_tokens()` call
   - Token usage is now passed directly when storing messages
   - Cleaner flow for token tracking

**Issue Fixed**:
- **Root Cause**: Token usage was not being saved when AI messages were stored
- **Problem**: `add_message()` calls were not passing the `$tokens_used` parameter
- **Solution**: Modified flow to capture and store token usage when messages are saved

**Dashboard Impact**:
- Total Tokens Used now properly tracks and displays token consumption
- Analytics will show accurate token usage for cost monitoring
- Token tracking works for both shortcode and global chatbots

## July 19, 2025 - Global Chatbot Position Fix

**Prompt**: "the position placement option for the GDPR is not working, The Global chat is only showing up in the bottom right hand corner even when left side is selected."

**Files Modified**:

1. `public/class-a1ai-public.php` - Fixed global position retrieval:
   - Added `$global_position` variable to retrieve position from global settings
   - Position is now properly passed to the template

2. `public/partials/a1ai-global-chatbot.php` - Fixed position usage:
   - Changed from using `$settings['position']` to `$global_position`
   - Position now correctly uses global settings instead of chatbot settings

3. `public/css/a1ai-public.css` - Enhanced CSS specificity:
   - Made positioning classes more specific with `.a1ai-global-chatbot-container.a1ai-position-*`
   - Added `!important` declarations to prevent CSS conflicts
   - Added explicit `left: auto` and `right: auto` to prevent positioning conflicts

**Issue Fixed**:
- **Root Cause**: Global chatbot was using position from chatbot settings instead of global settings
- **Problem**: Position setting in admin was not being applied to the global chatbot
- **Solution**: Properly retrieve and use global position setting in template

**User Experience Impact**:
- Global chatbot now correctly positions based on admin settings
- Bottom-left and bottom-right positioning now work as expected
- Enhanced CSS specificity prevents theme conflicts

## July 19, 2025 - GDPR Overlay Fix: Prevent Immediate Display

**Prompt**: "Try again, The GDPR is still showing up on the page when the page initially loads"

**Files Modified**:

1. `public/css/a1ai-public.css` - Fixed GDPR overlay display:
   - Changed default display from `flex` to `none` for `.a1ai-gdpr-overlay`
   - Added comment explaining that overlay is shown by JavaScript when needed

2. `public/js/a1ai-public.js` - Updated GDPR consent logic:
   - Modified `setupGDPRConsent()` to not show overlay immediately
   - Overlay now only appears when user tries to interact with chatbot
   - Maintains proper consent checking and storage functionality

**Issue Fixed**:
- **Root Cause**: GDPR overlay was set to `display: flex` by default in CSS
- **Problem**: Overlay appeared immediately on page load instead of only when needed
- **Solution**: Hide overlay by default and only show it when user attempts to interact

**User Experience Impact**:
- GDPR overlay no longer appears immediately when page loads
- Overlay only shows when user tries to send a message or interact with chatbot
- Maintains proper GDPR compliance while improving user experience

## July 19, 2025 - Security Fix: Redundant Nonce Verification

**Prompt**: "When I am trying to save a new chatbot I get this message Security check failed."

**Files Modified**:

1. `admin/class-a1ai-admin.php` - Fixed redundant nonce verification:
   - Removed duplicate nonce verification in `save_chatbot()` method
   - Removed duplicate nonce verification in `save_settings()` method
   - Removed duplicate nonce verification in `delete_chatbot()` method
   - Removed duplicate nonce verification in `get_analytics()` method
   - Added proper CS comments to disable nonce verification warnings
   - Nonce verification is already handled in `handle_admin_ajax()` method

**Issue Fixed**:
- **Root Cause**: Double nonce verification was causing the security check to fail
- **Problem**: Both `handle_admin_ajax()` and individual methods were verifying the same nonce
- **Solution**: Removed redundant nonce verification from individual methods since it's already handled at the AJAX entry point

**Security Impact**:
- Nonce verification still occurs at the proper entry point (`handle_admin_ajax()`)
- Eliminates false positive security failures
- Maintains proper WordPress security standards
- Added CS comments to properly document nonce verification flow

## July 19, 2025 - WordPress Coding Standards Compliance (Part 2)

**Prompt**: Fixed remaining SQL interpolation issues in prepared statements

**Files Modified**:

1. `includes/class-a1ai-data-manager.php` - Fixed SQL query preparation:
   - Separated SQL preparation from query execution
   - Properly concatenated table names outside of prepare statements
   - Used separate variables for SQL queries for better readability

2. `includes/class-a1ai-migration.php` - Fixed SQL query preparation:
   - Used proper concatenation for table names
   - Added appropriate phpcs comments for necessary exceptions
   - Separated SQL preparation from execution

**Standards Compliance**:
- ✅ **SQL Preparation**: All SQL queries now properly separate table names from prepared statements
- ✅ **CS Comments**: Added specific comments for PreparedSQL.InterpolatedNotPrepared exceptions
- ✅ **Query Structure**: Improved query structure with separate preparation and execution steps

**Improvements**:
- Better code readability with separate SQL preparation variables
- Clearer distinction between static table names and dynamic parameters
- Proper handling of system table names in queries

## July 19, 2025 - WordPress Coding Standards Compliance

**Prompt**: Fixed WordPress coding standards violations including nonce escaping, database query preparation, and caching implementation

**Files Modified**:

1. `admin/partials/a1ai-admin-chatbot-edit.php` - Added `esc_attr()` to nonce output for proper escaping
2. `admin/partials/a1ai-admin-settings.php` - Added `esc_attr()` to nonce output for proper escaping
3. `includes/class-a1ai-data-manager.php` - Fixed database queries:
   - Added proper caching with `wp_cache_get()` and `wp_cache_set()`
   - Fixed interpolated variables in prepared statements using `{$variable}` syntax
   - Added CS comments to disable/enable specific warnings where appropriate
   - Implemented cache invalidation for write operations
4. `includes/class-a1ai-migration.php` - Fixed database queries:
   - Added proper CS comments for migration operations
   - Fixed interpolated variables in prepared statements
   - Added schema change comments for DROP TABLE operations

**Standards Compliance**:
- ✅ **Nonce Escaping**: All nonce outputs now properly escaped with `esc_attr()`
- ✅ **Database Queries**: All queries use proper prepared statements with placeholders
- ✅ **Caching**: Implemented WordPress object caching for read operations
- ✅ **CS Comments**: Added appropriate phpcs disable/enable comments for necessary operations
- ✅ **Variable Interpolation**: Fixed all interpolated variables in SQL queries

**Performance Improvements**:
- Added caching for system prompts and custom instructions (1-hour cache)
- Proper cache invalidation on write operations
- Reduced database queries through intelligent caching

## July 19, 2025 - Security Fix: Nonce Verification

**Prompt**: "I went to create a new chatbot and it says security check failed when I went to save it"

**Files Modified**:

1. `admin/partials/a1ai-admin-chatbot-edit.php` - Fixed nonce mismatch by changing from `wp_nonce_field('a1ai_save_chatbot', 'a1ai_chatbot_nonce')` to `<input type="hidden" name="nonce" value="<?php echo wp_create_nonce('a1ai_admin_nonce'); ?>" />`
2. `admin/partials/a1ai-admin-settings.php` - Added missing nonce field for settings form: `<input type="hidden" name="nonce" value="<?php echo wp_create_nonce('a1ai_admin_nonce'); ?>" />`

**Issue Fixed**:
- **Root Cause**: Nonce mismatch between form generation and AJAX verification
- **Problem**: Form was creating nonce with action `'a1ai_save_chatbot'` but JavaScript was sending nonce created with action `'a1ai_admin_nonce'`
- **Solution**: Standardized all admin forms to use the same nonce action `'a1ai_admin_nonce'`

**Security Impact**:
- All admin form submissions now properly verify nonces
- Prevents CSRF attacks on chatbot creation and settings updates
- Ensures proper WordPress security standards compliance

## July 19, 2025 - Database Structure Enhancement

**Prompt**: "review the sql tables and see if there is a table and column for system prompt or custom instructions. if not create them in a way that makes sense, like creating their own dedicated table"

**Files Created/Modified**:

1. `a1.sql` - Added new tables `wp_a1ai_system_prompts` and `wp_a1ai_custom_instructions` with proper indexes and constraints
2. `includes/class-a1ai-migration.php` - Created migration class to handle database schema updates and data migration from JSON storage
3. `includes/class-a1ai-data-manager.php` - Added methods for managing system prompts and custom instructions:
   - `get_system_prompt()`
   - `save_system_prompt()`
   - `get_custom_instructions()`
   - `save_custom_instruction()`
   - `update_custom_instruction()`
   - `delete_custom_instruction()`
4. `DATABASE_STRUCTURE.md` - Created comprehensive documentation for the new database structure

**Changes**:
- **New Tables**: Created dedicated tables for system prompts and custom instructions instead of storing them in JSON
- **Better Performance**: Direct database queries instead of JSON parsing
- **Enhanced Functionality**: Support for multiple custom instructions with priority ordering and categorization
- **Migration System**: Automatic migration from existing JSON storage to new dedicated tables
- **Version Control**: System prompts support versioning with active/inactive states
- **Data Integrity**: Proper indexing, constraints, and sanitization
- **Scalability**: Foundation for advanced AI configuration features

**Benefits**:
- Improved query performance for AI configuration data
- Better data management and backup capabilities
- Support for complex AI configurations
- Historical tracking of system prompts and instructions
- Enhanced functionality for future features

## May 21, 2025 - Phase 5: OpenAI Integration

**Prompt**: "continue on to phase 5 and finish anything else in the rebuild.md file"

**Files Created/Modified**:

1. `includes/class-a1ai-openai.php` - Created a comprehensive OpenAI integration class to handle API requests, message formatting, and response processing.
2. `public/class-a1ai-public.php` - Updated the process_ai_message method to use the new OpenAI integration.
3. `includes/class-a1ai-data-manager.php` - Added get_conversation_messages and update_message_tokens methods to support OpenAI integration.
4. `admin/partials/a1ai-admin-settings.php` - Updated the API key field to use the correct option name (a1ai_openai_api_key).
5. `admin/class-a1ai-admin.php` - Updated the save_settings method to save the OpenAI API key with the correct option name.

**Changes**:
- Implemented OpenAI API connection with proper error handling and security
- Added conversation context management to maintain history and coherent responses
- Created token usage tracking for analytics and billing purposes
- Implemented message formatting according to OpenAI's requirements
- Added proper settings for API key management
- Updated admin interface to configure OpenAI-specific settings
- Implemented fallback responses for API failure scenarios
- Added proper error logging

**Next Steps**:
- Testing with real OpenAI API credentials
- Optimizing conversation context for token efficiency
- Adding more AI models as they become available

## May 20, 2025 - Phase 2: Database and Data Management

**Prompt**: "continuue to phase 2"

**Files Created/Modified**:

1. `includes/class-a1ai-data-manager.php` - Created comprehensive data manager class with CRUD operations for chatbots, conversations, messages, and adjustments.
2. `includes/class-a1ai-activator.php` - Enhanced to create database tables during activation and establish default chatbot.
3. `includes/class-a1ai-deactivator.php` - Updated to handle proper cleanup during deactivation including scheduled events.
4. `uninstall.php` - Improved to properly remove database tables and options during uninstallation.
5. `includes/class-a1ai.php` - Updated to include data manager and add API/AJAX hooks and scheduled maintenance.
6. `admin/class-a1ai-admin.php` - Enhanced with data manager support and basic admin menu structure.
7. `public/class-a1ai-public.php` - Updated with data manager support and placeholder public functionality.

**Changes**:
- Created comprehensive database tables for chatbots, conversations, messages, and adjustments
- Implemented complete CRUD operations for all database tables
- Added proper data sanitization and validation throughout
- Created database table creation and management during activation
- Added usage statistics functionality for analytics
- Added daily maintenance for data cleanup based on retention settings
- Implemented session management for tracking conversations
- Enhanced admin and public classes with data manager integration
- Added security with proper nonce checks and user capability verification

**Next Steps**:
- Phase 3: Implement admin interface functionality

## May 20, 2025 - Phase 1: Core Structure and Security

**Prompt**: "We are starting over with a1ai. Review the rebuild.md file and build out phase 1."

**Files Created/Modified**:

1. `a1ai.php` - Created the main plugin file with proper headers, version definitions, and core loading functionality.
2. `includes/class-a1ai-loader.php` - Implemented the loader class for managing WordPress hooks.
3. `includes/class-a1ai-i18n.php` - Created internationalization class for text domain loading.
4. `includes/class-a1ai-activator.php` - Implemented plugin activation logic with default options.
5. `includes/class-a1ai-deactivator.php` - Created plugin deactivation handler.
6. `includes/class-a1ai.php` - Developed the main plugin class that ties all components together.
7. `admin/class-a1ai-admin.php` - Added placeholder admin class for Phase 3.
8. `public/class-a1ai-public.php` - Added placeholder public class for Phase 4.
9. `uninstall.php` - Created uninstall file with basic cleanup functionality.
10. Added `index.php` files in all directories to prevent directory listing.

**Changes**:
- Set up proper WordPress plugin structure following best practices
- Implemented security measures including direct file access prevention
- Created the loader system for managing actions, filters, and shortcodes
- Used proper prefixing throughout the codebase
- Maintained consistent text domain usage (`a1ai`)
- Added comprehensive plugin documentation with PHPDoc comments
- Implemented proper plugin activation/deactivation hooks

**Next Steps**:
- Phase 2: Implement database tables and data management


