# AIAuto WordPress Cron Job

## Overview

The AIAuto plugin includes an automated WordPress cron job that runs every 5 minutes to process pending post generation requests. This cron job automatically processes the first row in the `aiauto_generate_posts` table where `status = 'To Do'`.

## How It Works

### 1. Automatic Scheduling
- **Frequency**: Every 5 minutes (300 seconds)
- **Hook**: `aiauto_process_posts_cron`
- **Auto-start**: Automatically scheduled when plugin is activated
- **Auto-cleanup**: Automatically removed when plugin is deactivated

### 2. Processing Flow

#### **Step 1 Processing (Generate Chapters)**
1. **Find Pending Post**: Gets the first row with `status = 'To Do'`
2. **Update Status**: Changes status to `'Processing'`
3. **Execute Step 1**: Runs the chapter generation process
4. **Save Data**: Stores chapters and subchapters in database tables
5. **Update Status**: Changes status to `'Generated Chapters'`

#### **Step 2 Processing (Generate Content)**
6. **Find Chapters Post**: Gets the first row with `status = 'Generated Chapters'`
7. **Retrieve Data**: Loads saved chapters and subchapters from database
8. **Execute Step 2**: Generates content for chapters and subchapters
9. **Update Content**: Updates database tables with generated content
10. **Status Update**: Changes status to `'Generated Content'`

#### **Step 3 Processing (Generate Metadata)**
11. **Execute Step 3**: Generates introduction, conclusion, and SEO metadata
12. **Update Post Info**: Saves all metadata to `aiauto_post_information` table
13. **Update Chapters**: Saves image information to `aiauto_chapters` table
14. **Status Update**: Changes status to `'Generated Metadata'`

#### **Step 4 Processing (Generate Images)**
15. **Check Image Setting**: Verifies `generate_image` field in `aiauto_generate_posts`
16. **Conditional Execution**: 
    - If `generate_image = 'yes'`: Generates images for chapters and main post
    - If `generate_image = 'no'`: Bypasses image generation
17. **Chapter Images**: Creates images for each chapter using stored prompts (if enabled)
18. **Featured Image**: Generates main post featured image (if enabled)
19. **Status Update**: 
    - `'Generated Images'` if images were generated
    - `'Completed (No Images)'` if image generation was disabled

#### **Step 5 Processing (Merge Content & Create Post)**
20. **Content Retrieval**: Gets post information and chapters data from database
21. **Content Merging**: Merges all content using `merge_content` function
22. **WordPress Post Creation**: Creates final post using `create_post` function
23. **Final Status**: Changes status to `'Completed'` with WordPress post ID

#### **Execution Order**
- **Every 5 minutes**: Cron job runs
- **First Priority**: Process posts with `status = 'To Do'` (Step 1)
- **Second Priority**: Process posts with `status = 'Generated Chapters'` (Step 2)
- **Independent Processing**: Each step can run independently

### 3. Database Operations

#### **Step 1: Chapters and Subchapters Generation**
- **Chapters Table** (`aiauto_chapters`)
  - Inserts each generated chapter
  - Links to the parent post via `post_id`
  - Stores chapter title and empty content (for future steps)

- **Subchapters Table** (`aiauto_subchapters`)
  - Splits comma-separated subchapters from each chapter
  - Inserts each subchapter individually
  - Links to parent chapter via `chapter_id`
  - Stores subchapter title and empty content (for future steps)

- **Post Information Table** (`aiauto_post_information`)
  - Saves research overview data
  - Links to parent post via `post_id`
  - Stores comprehensive research findings

#### **Step 2: Content Generation**
- **Chapters Table** (`aiauto_chapters`)
  - Updates existing chapters with generated content
  - Links content to chapter via `id`
  - Stores full chapter content in `content` field

- **Subchapters Table** (`aiauto_subchapters`)
  - Updates existing subchapters with generated content (if deeper research enabled)
  - Links content to subchapter via `id`
  - Stores full subchapter content in `content` field

#### **Step 3: Metadata Generation**
- **Post Information Table** (`aiauto_post_information`)
  - Updates existing post information with generated metadata
  - Stores introduction, conclusion, title, slug, SEO data
  - Links metadata to post via `post_id`
  - Includes tags, categories, and Google-friendly excerpts

- **Chapters Table** (`aiauto_chapters`)
  - Updates existing chapters with image information
  - Stores image title, caption, alt text, and prompt
  - Links image data to chapter via `id`

#### **Step 4: Conditional Image Generation**
- **Image Setting Check**: Verifies `generate_image` field in `aiauto_generate_posts`
- **Conditional Processing**:
  - **If `generate_image = 'yes'`**:
    - **Chapters Table** (`aiauto_chapters`): Updates with generated image URLs
    - **Generate Posts Table** (`aiauto_generate_posts`): Updates with featured image URL
  - **If `generate_image = 'no'`**:
    - **Bypasses**: Image generation completely
    - **Status Update**: Sets status to `'Completed (No Images)'`
- **Resource Optimization**: Saves API calls and processing time when images not needed

#### **Step 5: Content Merging & WordPress Post Creation**
- **Generate Posts Table** (`aiauto_generate_posts`): Retrieves original form data and settings
- **Post Information Table** (`aiauto_post_information`): Retrieves introduction, conclusion, and metadata
- **Chapters Table** (`aiauto_chapters`): Retrieves all chapter content and image data
- **Subchapters Table** (`aiauto_subchapters`): Retrieves subchapter content (only if deeper research enabled)
- **Conditional Processing**: 
  - If `deeper_research = 'yes'`: Includes subchapters in content merging
  - If `deeper_research = 'no'`: Bypasses subchapter processing
- **Content Merging**: Uses enhanced `merge_content` function to combine all content
- **WordPress Integration**: Creates final post using `create_post` function
- **Database Update**: Stores WordPress post ID in `aiauto_generate_posts.wordpress_post_id`
- **Final Status**: Updates status to `'Completed'`

#### **Independent Processing Benefits**
- **Parallel Processing**: Multiple posts can be in different stages
- **Fault Tolerance**: Step failures don't affect other steps
- **Resource Management**: Each step can be optimized independently
- **Queue Management**: Natural progression through processing stages

### 4. Error Handling
- **Try-Catch**: Wraps processing in exception handling
- **Status Updates**: Updates post status to `'Failed'` on errors
- **Error Logging**: Saves error details to `error_log` column
- **System Logging**: Logs errors to WordPress error log

### 5. Database Methods Added
- **`get_first_pending_post()`**: Gets first post with `status = 'To Do'`
- **`get_first_chapters_post()`**: Gets first post with `status = 'Generated Chapters'`
- **`get_generate_post_by_id()`**: Gets complete post data by ID
- **`update_chapter_content()`**: Updates chapter content and title in database
- **`update_subchapter_content()`**: Updates subchapter content and title in database
- **`update_post_information()`**: Updates post information with metadata
- **`update_generate_post_wordpress_id()`**: Stores WordPress post ID for reference
- **`get_saved_chapters_data()`**: Retrieves saved chapters for content generation
- **`insert_or_update_post_information()`**: Creates or updates post information records

## Configuration

### Custom Schedule
The cron job uses a custom schedule called `'every_2_minutes'`:
```php
$schedules['every_2_minutes'] = array(
    'interval' => 300, // 5 minutes in seconds
'display' => 'Every 5 Minutes'
);
```

### WordPress Cron vs System Cron
- **WordPress Cron**: Uses WordPress's built-in cron system
- **Dependency**: Relies on site traffic to trigger execution
- **Alternative**: Can be replaced with system cron for more reliability

## Manual Testing

### Admin Interface
Navigate to: **AI Automation Pro → Manual Trigger**
- **Button**: "Trigger Cron Job Now"
- **Function**: Manually executes the cron job
- **Status**: Shows next scheduled run time

### Code Execution
```php
// Manually trigger the cron job
do_action('aiauto_process_posts_cron');
```

## Database Schema Updates

### New Column Added
The `aiauto_post_information` table now includes:
- `research_overview` (longtext) - Stores research findings

### Table Relationships
```
aiauto_generate_posts (1) ←→ (many) aiauto_chapters
aiauto_chapters (1) ←→ (many) aiauto_subchapters
aiauto_generate_posts (1) ←→ (1) aiauto_post_information
```

## Monitoring and Debugging

### Status Tracking
- **To Do**: Post waiting for processing
- **Processing**: Currently being processed
- **Generated Chapters**: Chapters and subchapters successfully generated
- **Generated Content**: Content for chapters and subchapters successfully generated
- **Generated Metadata**: Introduction, conclusion, and SEO metadata generated
- **Generated Images**: Images for chapters and main post successfully generated
- **Completed (No Images)**: Processing completed without image generation
- **Completed**: All processing completed, WordPress post created
- **Failed**: Processing failed (check error_log)

### Error Logs
- **Database**: Check `error_log` column in `aiauto_generate_posts`
- **System**: Check WordPress error log for cron-related messages
- **Format**: `AIAuto Cron: [message]`

### Performance Considerations
- **Timeout**: Set to 25 minutes (1500 seconds)
- **Memory**: No specific memory limits set
- **Database**: Uses prepared statements for security
- **API Calls**: Includes Perplexity and OpenAI API calls

## Troubleshooting

### Common Issues

#### 1. Cron Not Running
- **Check**: WordPress cron system status
- **Solution**: Use system cron or increase site traffic

#### 2. Posts Stuck in "Processing"
- **Check**: Error logs and database status
- **Solution**: Manual status reset or error resolution

#### 3. Posts Stuck in "Generated Chapters"
- **Check**: Step 2 processing logs and database status
- **Solution**: Verify chapters data exists, check API keys for content generation

#### 4. Posts Stuck in "Generated Content"
- **Check**: Step 3 processing logs and database status
- **Solution**: Verify content generation completed, check API keys for metadata generation

#### 5. API Timeouts
- **Check**: OpenAI and Perplexity API keys
- **Solution**: Verify API configuration and limits

### Debug Mode
Enable WordPress debug logging to see detailed cron execution:
```php
// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
```

## Future Enhancements

### Planned Features
- **Queue Management**: Process multiple posts in sequence
- **Retry Logic**: Automatic retry for failed posts
- **Progress Tracking**: Real-time progress updates
- **Batch Processing**: Handle multiple posts per cron run

### Customization Options
- **Schedule**: Configurable cron frequency
- **Batch Size**: Number of posts processed per run
- **Priority**: Post processing priority system
- **Notifications**: Email/SMS alerts for completion/failures

## Security Considerations

### Access Control
- **Capability Check**: Requires `manage_options` capability
- **Nonce Verification**: CSRF protection for manual triggers
- **Input Sanitization**: All data sanitized before database operations

### API Security
- **Key Storage**: API keys stored in WordPress options
- **Request Validation**: Input validation and sanitization
- **Error Handling**: No sensitive data exposed in error messages

## Support and Maintenance

### Regular Tasks
- **Monitor**: Check cron job execution logs
- **Cleanup**: Remove old failed/processed records
- **Update**: Keep API keys and configurations current

### Backup Strategy
- **Database**: Regular backups of plugin tables
- **Configuration**: Export plugin settings
- **Logs**: Archive error and execution logs

## Cron Job Troubleshooting

### Why Cron Might Not Run Every 5 Minutes

#### **1. WordPress Cron System Limitation**
- **Important**: WordPress cron is **NOT a real cron job**
- **How it works**: Only runs when someone visits the site
- **Reality**: "Every 5 minutes" means "at most every 5 minutes when site is visited"
- **Problem**: If no one visits the site for 5 minutes, cron won't run

#### **2. Site Traffic Issues**
- **Low traffic sites**: Cron may not run frequently
- **Development environments**: Often have no regular visitors
- **Local installations**: No external traffic to trigger cron

#### **3. WordPress Configuration**
- **DISABLE_WP_CRON**: May be set to true in wp-config.php
- **Server restrictions**: Some hosting providers limit cron execution
- **Plugin conflicts**: Other plugins may interfere with cron scheduling

### Solutions

#### **Immediate Testing**
1. **Use Manual Trigger**: Go to **AI Automation Pro > Manual Trigger**
2. **Check Cron Status**: Go to **AI Automation Pro > Cron Status**
3. **Test with cron-test.php**: Use the debug file (remove after testing)

#### **For Development/Testing**
- **Visit site regularly**: Manually trigger cron execution
- **Use manual triggers**: Test functionality without waiting
- **Monitor logs**: Check error logs for issues

#### **For Production**
- **Real cron job**: Set up server-level cron
- **Regular traffic**: Ensure site gets regular visitors
- **Monitoring**: Set up alerts for cron failures

### Server Cron Setup (Recommended for Production)

```bash
# Add to server crontab (runs every 5 minutes)
*/5 * * * * curl -s "https://yoursite.com/wp-cron.php?doing_wp_cron" > /dev/null 2>&1

# Or use wget
*/2 * * * * wget -q -O /dev/null "https://yoursite.com/wp-cron.php?doing_wp_cron"
```

### Debugging Steps

1. **Check if cron is scheduled**
   - Go to **AI Automation Pro > Cron Status**
   - Verify next scheduled run time

2. **Test manual execution**
   - Use **AI Automation Pro > Manual Trigger**
   - Check for success/error messages

3. **Review error logs**
   - Check WordPress error log
   - Look for "AIAuto Cron:" messages

4. **Verify database tables**
   - Ensure all required tables exist
   - Check table structure and data

5. **Test with sample data**
   - Create a test post request
   - Monitor processing through all steps 