# AI SEO Article Generator - Claude Code Development Guidelines

## 🎯 Project Overview
**Plugin Name**: AI SEO Article Generator  
**Version**: 1.0.3  
**Purpose**: WordPress plugin for AI-powered SEO content generation using Claude and OpenAI  
**Primary Language**: Hebrew with English support  
**Status**: Production-ready, WordPress.org compliant

## 📚 Knowledge Base Location
All development knowledge is organized in: `/docs/knowledgebase/`
- **Start Here**: `/docs/knowledgebase/00-INDEX.md`
- **Critical Issues**: `/docs/knowledgebase/02-DEVELOPMENT-PATTERNS/wordpress-quirks.md`
- **Architecture**: `/docs/knowledgebase/01-ARCHITECTURE/plugin-structure.md`

## 🚨 CRITICAL RULES - MUST FOLLOW

### 1. WordPress Development Standards
**ALWAYS follow WordPress coding standards for EVERY feature:**
- Use WordPress functions for database operations (`$wpdb`)
- Sanitize ALL inputs: `sanitize_text_field()`, `wp_kses_post()`, etc.
- Escape ALL outputs: `esc_html()`, `esc_attr()`, `esc_url()`, etc.
- Use nonces for ALL forms and AJAX requests
- Check capabilities: `current_user_can('manage_options')`
- Use WordPress hooks system (actions and filters)
- Follow WordPress naming conventions (snake_case for functions)

### 2. JSON Data Handling in WordPress
```php
// CRITICAL: Always unslash WordPress POST data containing JSON
$json_data = wp_unslash($_POST['json_data']);

// NEVER use wp_kses_post() on JSON data - it corrupts it
// Instead, decode first, sanitize values, then re-encode
```

### 3. Hebrew/UTF-8 Support
```php
// Always verify encoding
if (!mb_check_encoding($data, 'UTF-8')) {
    $data = mb_convert_encoding($data, 'UTF-8', 'auto');
}

// Database tables must use utf8mb4
$charset_collate = $wpdb->get_charset_collate();
```

### 4. Security First
- **Never trust user input** - sanitize everything
- **Escape late, escape often** - right before output
- **Validate capabilities** - check user permissions
- **Use prepared statements** - prevent SQL injection
- **Implement nonces** - prevent CSRF attacks

## 📋 Development Workflow

### Problem Analysis Phase
1. **Define the specific problem** with debug logs and console output
2. **Ask clarifying questions** when requirements are unclear
3. **Update context** using existing knowledge base before starting
4. Check `/docs/knowledgebase/` for existing patterns
5. Review WordPress Codex for standard approaches

### Planning & Approach Phase
1. **Present implementation plan** before writing any code
2. **Suggest multiple options** rather than immediately coding
3. **Let user choose** from proposed solutions
4. Consider security measures (input sanitization, output escaping)
5. Plan for Hebrew/RTL implications
6. Design error handling and user feedback strategy

### Implementation Phase
1. **Follow YAGNI and KISS principles** - keep it simple
2. **Create modular files** - avoid monolithic code
3. **Keep files under 25,000 tokens** for optimal processing
4. Follow existing code patterns in the plugin
5. Use WordPress functions over PHP natives
6. Add proper error handling with user-friendly messages
7. **Run self-tests** to validate implementation

### Testing & Validation Phase
1. Test all edge cases (empty data, special characters, long content)
2. Test with both Hebrew and English content
3. Verify security (nonces, capabilities, escaping)
4. **Run validation scripts** to verify understanding
5. Verify WordPress coding standards compliance

### Documentation & Completion Phase
1. **Document lessons learned** in knowledge base
2. Update relevant documentation in `/docs/knowledgebase/`
3. **Explain usage and testing procedures** for new features
4. **Provide concise commit summary**:
   - One descriptive title
   - One sentence explaining changes
5. **Record conversation summary** before context limits

## 🏗️ Architecture Patterns

### Class Structure
```php
class AI_SEO_Article_Generator_NewFeature {
    private $plugin;
    
    public function __construct() {
        $this->plugin = ai_seo_article_generator();
        $this->init_hooks();
    }
    
    private function init_hooks() {
        add_action('admin_menu', array($this, 'add_menu_item'));
        add_action('wp_ajax_feature_action', array($this, 'ajax_handler'));
    }
}
```

### AJAX Handler Pattern
```php
public function ajax_handler() {
    // 1. Verify nonce
    if (!check_ajax_referer('ai-seo-article-generator-nonce', 'nonce', false)) {
        wp_send_json_error(__('Security check failed', 'ai-seo-article-generator'));
    }
    
    // 2. Check capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('Insufficient permissions', 'ai-seo-article-generator'));
    }
    
    // 3. Sanitize inputs
    $data = isset($_POST['data']) ? sanitize_text_field($_POST['data']) : '';
    
    // 4. Process
    try {
        $result = $this->process_data($data);
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error($e->getMessage());
    }
}
```

### JavaScript Pattern
```javascript
(function($) {
    'use strict';
    
    window.aiSeoArticleGenerator = window.aiSeoArticleGenerator || {};
    
    aiSeoArticleGenerator.newFeature = {
        init: function() {
            this.bindEvents();
        },
        
        bindEvents: function() {
            // Use event delegation for dynamic content
            $(document).on('click', '.feature-button', this.handleClick.bind(this));
        },
        
        handleClick: function(e) {
            e.preventDefault();
            
            var data = {
                action: 'ai_seo_article_generator_feature',
                nonce: ai_seo_article_generator.nonce,
                // additional data
            };
            
            $.ajax({
                url: ai_seo_article_generator.ajax_url,
                type: 'POST',
                data: data,
                beforeSend: function() {
                    // Show loading state
                }
            }).done(function(response) {
                if (response.success) {
                    // Handle success
                } else {
                    // Show error
                }
            }).fail(function() {
                // Handle failure
            });
        }
    };
    
    $(document).ready(function() {
        aiSeoArticleGenerator.newFeature.init();
    });
})(jQuery);
```

## 🔍 Common Patterns Reference

### Database Operations
```php
global $wpdb;
$table_name = $wpdb->prefix . 'ai_seo_article_feature';

// Insert
$wpdb->insert(
    $table_name,
    array('column' => $value),
    array('%s') // Format
);

// Select with prepare
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM $table_name WHERE id = %d",
        $id
    )
);
```

### Internationalization
```php
// Text domain: 'ai-seo-article-generator'
__('Text to translate', 'ai-seo-article-generator');
_e('Echo this text', 'ai-seo-article-generator');
esc_html__('Escaped text', 'ai-seo-article-generator');

// With placeholders
sprintf(
    /* translators: %s: Item name */
    __('Delete %s?', 'ai-seo-article-generator'),
    $item_name
);
```

### Error Handling
```php
try {
    // Risky operation
    $result = $this->risky_operation();
} catch (Exception $e) {
    // Log for developers
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('AI SEO Generator Error: ' . $e->getMessage());
    }
    
    // User-friendly message
    return new WP_Error(
        'operation_failed',
        __('Operation failed. Please try again.', 'ai-seo-article-generator')
    );
}
```

## 📝 Git Workflow

### Branch Strategy
- `main` - Production-ready code for WordPress.org
- `dev-wordpress.org` - Development branch
- `feature/*` - Feature branches

### Commit Messages
```
feat: Add user feedback system
fix: Resolve Hebrew text encoding issue
docs: Update knowledgebase with new patterns
style: Apply WordPress coding standards
refactor: Improve AJAX error handling
```

### Before Committing
1. Test functionality thoroughly
2. Verify WordPress coding standards
3. Update documentation if needed
4. Ensure no debug code remains
5. Check for hardcoded values

## 🚀 Testing Checklist

### Functionality Testing
- [ ] Feature works with Hebrew content
- [ ] Feature works with English content
- [ ] Empty data handled gracefully
- [ ] Long content (4000+ words) handled
- [ ] Special characters handled
- [ ] Error states show user-friendly messages

### Security Testing
- [ ] Nonces verified on all AJAX calls
- [ ] Capabilities checked
- [ ] All inputs sanitized
- [ ] All outputs escaped
- [ ] SQL injection prevented
- [ ] XSS prevented

### WordPress Standards
- [ ] Proper hook usage
- [ ] WordPress functions used
- [ ] Internationalization implemented
- [ ] Proper enqueuing of scripts/styles
- [ ] Database operations use $wpdb
- [ ] Options API used correctly

## 🔧 Debugging

### Enable Debug Mode
```php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
define('AI_SEO_ARTICLE_GENERATOR_DEBUG', true);
```

### Debug Locations
- WordPress debug log: `/wp-content/debug.log`
- Browser console for JavaScript errors
- Network tab for AJAX requests

## 📞 Support Resources

### Internal
- Knowledge base: `/docs/knowledgebase/00-INDEX.md`
- Common issues: `/docs/knowledgebase/05-TROUBLESHOOTING/common-issues.md`
- Architecture: `/docs/knowledgebase/01-ARCHITECTURE/plugin-structure.md`

### External
- [WordPress Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/)
- [WordPress Plugin Handbook](https://developer.wordpress.org/plugins/)
- [WordPress Security](https://developer.wordpress.org/plugins/security/)

## ⚡ Quick Commands

### Check Plugin
```bash
# Run WordPress Plugin Check
wp plugin check ai-seo-article-generator

# PHP CodeSniffer
phpcs --standard=WordPress .
```

### Update SVN
```bash
cd svn-repo
svn update
cp -r ../plugin-files/* trunk/
svn ci -m "Update message" --username ytrofr
```

## 🎯 Core Development Principles

### Technical Principles
1. **WordPress First**: Always use WordPress ways of doing things
2. **Security Always**: Never skip sanitization or escaping
3. **Hebrew Support**: Test everything with Hebrew content
4. **YAGNI**: You Aren't Gonna Need It - avoid over-engineering
5. **KISS**: Keep It Simple, Stupid - simplicity over complexity

### Process Principles
1. **Plan Before Code**: Present options, don't jump to implementation
2. **Modular Design**: Small, focused files over monolithic code
3. **Context Awareness**: Maintain and update context continuously
4. **User Choice**: Let users decide between proposed solutions
5. **Clear Communication**: Concise, descriptive documentation

### Quality Principles
1. **Best Practices**: Always use industry standards
2. **Self-Testing**: Validate your own implementation
3. **User Experience**: Clear messages and graceful error handling
4. **Documentation**: Record lessons learned and test results
5. **Prioritization**: Consider Impact, Priority, and Effort

---

**Last Updated**: January 2025  
**For**: Claude Code and development team  
**Critical**: This file contains project-specific guidelines that override general practices