# Nietos AI

AI-powered WordPress assistant for content management and site administration. Chat with your WordPress site using OpenAI's ChatGPT API.

## Features

- **Natural Language Interface**: Manage your WordPress site through conversation
- **Content Management**: Create, edit, and delete posts and pages
- **Media Management**: Upload and manage images with auto-generated alt text
- **Taxonomy Management**: Create, update, assign, and delete categories and tags
- **Comment Moderation**: Approve, reply to, and trash comments directly from chat
- **User Management**: Create and manage WordPress users safely
- **Widget Management**: Manage sidebar widgets and placements
- **Menu Management**: Create menus, assign locations, and manage menu items
- **Plugin Management**: Activate or deactivate plugins with safety checks
- **Block Editor Integration**: AI assistant directly in the Gutenberg editor
- **Bring Your Own Key (BYOK)**: Use your own OpenAI API key
- **Context-Aware**: AI knows which post/page you're currently editing
- **Safety First**: Confirms destructive actions and validates all operations
- **Premium Licensing**: Optional premium version with unlimited messages

## Requirements

- WordPress 6.0 or higher
- PHP 8.0 or higher
- Node.js 18+ and npm (for development)
- API key from [OpenAI](https://platform.openai.com/)

## Installation

### From Release

1. Download the latest release ZIP file
2. Go to WordPress Admin → Plugins → Add New → Upload Plugin
3. Upload the ZIP file and click "Install Now"
4. Activate the plugin
5. Go to Nietos AI → Settings to configure your API key

### From Source (Development)

1. Clone this repository into your WordPress plugins directory:
   ```bash
   cd wp-content/plugins
   git clone https://github.com/yourusername/nietos-ai.git
   cd nietos-ai
   ```

2. Install dependencies:
   ```bash
   npm install
   ```

3. Build the frontend:
   ```bash
   npm run build
   ```

4. Activate the plugin in WordPress admin

## Configuration

1. Navigate to **Nietos AI → Settings** in WordPress admin
2. Enter your OpenAI API key:
   - Get your key at https://platform.openai.com/api-keys
3. Select your preferred GPT model (GPT-4o, GPT-4o Mini, GPT-4 Turbo, etc.)
4. Adjust settings like max tokens and temperature (optional)
5. Click "Save Settings"

### Premium License (Optional)

The free version includes 5 AI messages per day. To unlock unlimited messages:

1. Purchase a premium license from [nietos-ai.com](https://nietos-ai.com/product/nietos-ai-premium-license/)
2. Navigate to **Nietos AI → Settings → Premium License**
3. Enter your license key in the format: `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX`
4. Click "Activate License"
5. You now have unlimited messages!

**Premium Features:**
- ✅ Unlimited AI messages per day
- ✅ Priority support
- ✅ Early access to new features

**License Management:**
- Each license can be activated on one WordPress site
- To move your license to a different site, first deactivate it from the old site
- License status is cached for 24 hours for optimal performance
- If you're offline, there's a 7-day grace period

## Usage

### Admin Dashboard Chat

1. Go to **Nietos AI** in the WordPress admin menu
2. Start chatting with the AI assistant
3. Ask it to perform tasks like:
   - "Create a new blog post about WordPress security"
   - "Edit the About page and change the title to 'About Us'"
   - "Upload this image and use it as the featured image"
   - "Create a new editor user named Sarah"

### Block Editor Sidebar

1. Open any post or page in the Block Editor
2. Click the three dots (⋮) in the top right
3. Select **Nietos AI** from the menu
4. The AI sidebar will open with context about the current post
5. Ask it to modify the current post:
   - "Add a conclusion paragraph"
   - "Change the heading color to blue"
   - "Insert an image gallery"

## Available Commands

The AI assistant can perform various operations:

### Content Operations
- Create new posts and pages
- Edit existing content
- Update titles, excerpts, and metadata
- Add, modify, or remove blocks
- Change post status (draft, publish, pending)
- Schedule posts

### Media Operations
- Upload images from URLs
- Edit image metadata (alt text, captions)
- Set featured images
- Manage media library

### Taxonomy Operations
- Create new categories and tags
- Update or delete existing terms (with confirmations)
- Assign categories or tags to posts and pages

### Comment Operations
- Approve comments awaiting moderation
- Reply to comments as the current user
- Move spammy or unwanted comments to trash (with confirmation)

### Widget Operations
- Create new widget instances
- Update widget settings
- Remove widgets from sidebars
- Assign widgets to specific sidebars and positions

### Menu Operations
- Create or rename navigation menus
- Assign menus to theme locations
- Add, update, or remove menu items

### User Operations
- Create new users with appropriate roles
- Update user profiles
- Change user roles (with safety checks)
- Delete users (with content reassignment)

### Settings Operations
- Update site title and tagline
- Modify permalink structure (with warnings)
- Change date/time formats
- Configure comment settings

### Plugin Operations
- Activate installed plugins
- Deactivate active plugins (with confirmation)

## Safety Features

Nietos AI includes several safety mechanisms:

- **Confirmation Required**: Destructive actions (delete, publish) require confirmation
- **Context Preservation**: Editing preserves existing content unless explicitly changed
- **Permission Checks**: Respects WordPress user capabilities
- **Input Validation**: All inputs are validated and sanitized
- **Operation Logging**: All operations are logged for audit

## Development

### Project Structure

```
nietos-ai/
├── nietos-ai.php              # Main plugin file
├── includes/                   # PHP backend classes
│   ├── class-nietos-ai.php
│   ├── class-api-handler.php
│   ├── class-security.php
│   └── ...
├── admin/                      # Admin page classes
├── prompts/                    # AI instruction system
│   ├── system-prompt.md
│   ├── instructions/
│   └── examples/
├── src/                        # React TypeScript source
│   ├── components/
│   ├── hooks/
│   ├── services/
│   └── types/
├── dist/                       # Built frontend assets
└── package.json
```

### Development Commands

```bash
# Install dependencies
npm install

# Start development server with hot reload
npm run dev

# Build for production
npm run build

# Type checking
npm run type-check
```

### Customizing AI Behavior

The AI's behavior is controlled through markdown files in the `prompts/` directory:

- **system-prompt.md**: Main system instructions
- **instructions/content.md**: Content operation guidelines
- **instructions/media.md**: Media operation guidelines
- **instructions/users.md**: User operation guidelines
- **instructions/settings.md**: Settings operation guidelines
- **instructions/taxonomy.md**: Category and tag management guidelines
- **instructions/comments.md**: Comment moderation guidelines
- **instructions/widgets.md**: Widget management guidelines
- **instructions/menus.md**: Navigation menu management guidelines
- **instructions/plugins.md**: Plugin activation/deactivation guidelines
- **examples/**: Example interactions and safety rules

Edit these files to customize how the AI responds to different requests.

### Extending with Hooks

Developers can extend Nietos AI using WordPress filters:

```php
// Modify system prompt
add_filter('nietos_ai_system_prompt', function($prompt, $context) {
    $prompt .= "\n\nCustom instructions here.";
    return $prompt;
}, 10, 2);

// Add custom tools/functions
add_filter('nietos_ai_tools', function($tools) {
    $tools[] = [
        'type' => 'function',
        'function' => [
            'name' => 'custom_operation',
            'description' => 'Perform a custom operation',
            'parameters' => [...]
        ]
    ];
    return $tools;
});

// Modify AI response
add_filter('nietos_ai_response', function($response, $request) {
    // Process or modify response
    return $response;
}, 10, 2);
```

## API Usage and Costs

Nietos AI uses the Bring Your Own Key (BYOK) model. You pay directly to OpenAI based on your usage:

- **OpenAI Pricing**: https://openai.com/pricing

Typical costs per request:
- Simple operations: $0.01 - $0.05
- Complex operations: $0.05 - $0.20

Monitor your usage in your OpenAI dashboard.

## Troubleshooting

### "API key not configured" error
- Go to Settings and enter your API key
- Make sure you've saved the settings
- Test the connection using the Test button (if available)

### "You've reached your daily message limit"
- Free version is limited to 5 messages per day
- Upgrade to Premium for unlimited messages
- Message count resets at midnight (your server's timezone)

### "License activation failed"
- Check that your license key is correct (32 characters with dashes)
- Ensure your site has internet connectivity to verify with the license server
- Make sure the license isn't already activated on another domain
- Contact support if the problem persists

### "Domain mismatch" error
- Your license is already activated on a different domain
- To move it, first deactivate from the old site at: **Nietos AI → Settings → Premium License → Remove License**
- Then activate it on the new site

### AI responses are slow
- This is normal for complex operations
- Response time depends on your chosen model
- Consider using faster models (GPT-4o Mini, GPT-3.5 Turbo)

### "Permission denied" errors
- Check that your WordPress user has appropriate capabilities
- Some operations require admin privileges

### Frontend not loading
- Make sure you've run `npm run build`
- Check that `dist/` directory exists with built files
- Clear WordPress and browser cache

## Security

- API keys are encrypted at rest using WordPress salts
- All operations respect WordPress capability system
- Input validation and output escaping on all data
- Nonce verification for all AJAX requests
- No direct database queries - uses WordPress functions

## Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test thoroughly
5. Submit a pull request

## Support

- **Issues**: https://github.com/yourusername/nietos-ai/issues
- **Documentation**: https://nietos-ai.com/docs
- **Discussions**: https://github.com/yourusername/nietos-ai/discussions

## License

GPL v2 or later - https://www.gnu.org/licenses/gpl-2.0.html

## Credits

Developed by the Nietos AI Team

Powered by:
- [ChatGPT](https://openai.com/chatgpt) by OpenAI
- [WordPress](https://wordpress.org/)
- [React](https://react.dev/)
- [TypeScript](https://www.typescriptlang.org/)

---

**Nietos AI** - Your intelligent WordPress assistant
