# Developer Documentation

## Plugin Architecture

### Core Components

1. **Main Plugin File** (`ai-seo-article-generator.php`)
   - Plugin initialization
   - Database table creation
   - Hook registration
   - Migration handling

2. **Admin Class** (`includes/class-ai-seo-article-generator-admin.php`)
   - Admin menu management
   - AJAX handlers
   - User interface
   - Settings management

3. **API Class** (`includes/class-ai-seo-article-generator-api.php`)
   - Claude API integration
   - OpenAI API integration
   - Request handling
   - Response parsing

4. **Generator Class** (`includes/class-ai-seo-article-generator-generator.php`)
   - Content generation logic
   - SEO optimization
   - Table of contents generation
   - Content analysis

5. **Background Processor** (`includes/class-ai-seo-article-generator-background-processor.php`)
   - Async job handling
   - Long article generation
   - Email notifications
   - Retry logic

### Database Schema

```sql
-- Article Drafts Table
CREATE TABLE {prefix}_ai_seo_article_generator_drafts (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    title varchar(255) NOT NULL,
    main_keyword varchar(255) NOT NULL,
    sub_keywords text,
    target_words int(6) DEFAULT 1000,
    structure_data longtext,
    content longtext,
    status varchar(20) DEFAULT 'draft',
    wp_post_id mediumint(9) DEFAULT NULL,
    word_count int(6) DEFAULT 0,
    outbound_links longtext,
    background_status varchar(20) DEFAULT 'none',
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

-- Structures Table
CREATE TABLE {prefix}_ai_seo_article_generator_structures (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    draft_id mediumint(9) NOT NULL,
    structure_json longtext NOT NULL,
    is_approved tinyint(1) DEFAULT 0,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

-- Saved Structures Table
CREATE TABLE {prefix}_ai_seo_article_generator_saved_structures (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    name varchar(255) NOT NULL,
    description text,
    main_keyword varchar(255) NOT NULL,
    sub_keywords text,
    target_words int(6) DEFAULT 1000,
    structure_data longtext NOT NULL,
    usage_count int(6) DEFAULT 0,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);
```

## API Integration

### Claude API

```php
// Configuration
$api_key = get_option('ai_seo_article_generator_api_key');
$api_url = 'https://api.anthropic.com/v1/messages';

// Request format
$request = array(
    'model' => 'claude-3-5-sonnet-20241022',
    'max_tokens' => $max_tokens,
    'messages' => array(
        array(
            'role' => 'user',
            'content' => $prompt
        )
    ),
    'temperature' => 0.7
);
```

### OpenAI API

```php
// Configuration  
$api_key = get_option('ai_seo_article_generator_openai_api_key');
$api_url = 'https://api.openai.com/v1/chat/completions';

// Request format
$request = array(
    'model' => $model, // gpt-4, gpt-4-turbo, gpt-3.5-turbo
    'messages' => array(
        array(
            'role' => 'user',
            'content' => $prompt
        )
    ),
    'max_tokens' => $max_tokens,
    'temperature' => 0.7
);
```

## AJAX Endpoints

### Structure Generation
- Action: `ai_seo_article_generator_generate_structure`
- Nonce: `ai_seo_article_generator_nonce`
- Parameters: `main_keyword`, `sub_keywords`, `target_words`

### Content Generation
- Action: `ai_seo_article_generator_generate_content`
- Nonce: `ai_seo_article_generator_nonce`
- Parameters: `structure`, `main_keyword`, `sub_keywords`, `target_words`

### Draft Management
- Save: `ai_seo_article_generator_save_draft`
- Load: `ai_seo_article_generator_load_draft`
- Delete: `ai_seo_article_generator_delete_draft`

## Hooks and Filters

### Actions
```php
// Before/after generation
do_action('ai_seo_article_generator_before_generate', $keyword, $type);
do_action('ai_seo_article_generator_after_generate', $content, $keyword);

// Structure saved
do_action('ai_seo_article_generator_structure_saved', $structure_id, $data);
```

### Filters
```php
// Modify prompts
$prompt = apply_filters('ai_seo_article_generator_prompt', $prompt, $type);

// Filter content
$content = apply_filters('ai_seo_article_generator_content', $content);

// Adjust timeouts
$timeout = apply_filters('ai_seo_article_generator_timeout', $timeout, $type);
```

## Debug Mode

Enable debug logging:
```php
update_option('ai_seo_article_generator_debug_logging', 1);
```

Debug logs are written using the `debug_log()` method in each class:
```php
private function debug_log($message, $data = null) {
    if (get_option('ai_seo_article_generator_debug_logging', 0)) {
        $log_message = 'AI SEO Article Generator: ' . $message;
        if ($data !== null) {
            $log_message .= ' - ' . wp_json_encode($data);
        }
        error_log($log_message);
    }
}
```

## Security Considerations

1. **Nonce Verification**: All AJAX requests verify nonces
2. **Capability Checks**: Admin capabilities required for all operations
3. **Data Sanitization**: All inputs sanitized with appropriate functions
4. **SQL Injection Prevention**: Prepared statements for all queries
5. **XSS Prevention**: Output escaping with `esc_html()`, `esc_attr()`, etc.

## Performance Optimization

1. **Background Processing**: Long articles processed asynchronously
2. **Chunked Responses**: Large API responses handled in chunks
3. **Database Indexes**: Proper indexes on frequently queried columns
4. **Caching**: Transient caching for API responses (where applicable)

## Testing

### Manual Testing Checklist
- [ ] API connection test
- [ ] Structure generation (< 1000 words)
- [ ] Content generation (< 2000 words)
- [ ] Background processing (> 2000 words)
- [ ] Draft saving/loading
- [ ] Structure library operations
- [ ] Hebrew content generation
- [ ] English content generation
- [ ] Error handling
- [ ] Timeout handling

### Common Issues

1. **Timeout Errors**
   - Enable background processing
   - Increase PHP execution time
   - Check server timeout settings

2. **API Errors**
   - Verify API key
   - Check API quota/limits
   - Enable debug mode for detailed logs

3. **Database Errors**
   - Ensure tables are created
   - Check MySQL strict mode compatibility
   - Verify charset/collation

## Contributing

1. Follow WordPress Coding Standards
2. Add proper documentation
3. Include security considerations
4. Test with both Claude and OpenAI
5. Ensure Hebrew/English compatibility

## Version History

See [readme.txt](readme.txt) for detailed changelog.