# WPForms to Mailjet Automation - Configuration Guide

## Overview

This plugin supports extensive customization through WordPress filters. You can modify settings without touching core plugin files, ensuring your customizations survive plugin updates.

## Quick Start

1. **Copy the sample configuration file:**
   ```bash
   cp wpfmj-config-sample.php wpfmj-config.php
   ```

2. **Edit `wpfmj-config.php`** with your preferred settings

3. **Save and upload** - Settings take effect immediately

The `wpfmj-config.php` file is automatically loaded by the plugin and is excluded from version control.

---

## Available Configuration Options

### 1. Error Log Retention Period

**Filter**: `wpfmj_error_log_retention_days`  
**Default**: 90 days  
**Range**: 7-365 days  
**Type**: Integer

Controls how long resolved error logs are kept before automatic deletion.

```php
add_filter('wpfmj_error_log_retention_days', function($days) {
    return 180; // Keep for 6 months
});
```

**Considerations:**
- **Shorter periods (7-30 days)**: Saves database space, good for high-volume sites
- **Longer periods (90-365 days)**: Better for audit trails and trend analysis
- **Optimal**: 90 days balances storage and historical data

---

### 2. API Rate Limit

**Filter**: `wpfmj_api_rate_limit`  
**Default**: 60 requests/minute  
**Range**: 10-300 requests/minute  
**Type**: Integer

Sets the maximum Mailjet API requests per minute per API key.

```php
add_filter('wpfmj_api_rate_limit', function($limit) {
    return 120; // Double the default
});
```

**Considerations:**
- **Lower limits (10-30)**: More conservative, prevents rate limit errors
- **Default (60)**: Balanced for most sites
- **Higher limits (120-300)**: For high-traffic sites, but monitor closely
- **Mailjet limit**: 300 requests/minute maximum

⚠️ **Warning**: Setting too high may cause Mailjet to reject requests.

---

### 3. Maximum Retry Attempts

**Filter**: `wpfmj_max_retry_attempts`  
**Default**: 3 attempts  
**Range**: 1-5 attempts  
**Type**: Integer

Number of retry attempts for failed API calls.

```php
add_filter('wpfmj_max_retry_attempts', function($attempts) {
    return 5; // Maximum persistence
});
```

**Retry Timing:**
- Attempt 1: Immediate
- Attempt 2: After 1 second
- Attempt 3: After 2 seconds
- Attempt 4: After 4 seconds
- Attempt 5: After 8 seconds

**Considerations:**
- **1 attempt**: Fast failure, good for testing
- **3 attempts (default)**: Balanced approach
- **5 attempts**: Maximum reliability, but slower failure detection

---

### 4. Email Notification Recipients

**Filter**: `wpfmj_failure_notification_emails`  
**Default**: WordPress admin email  
**Type**: Array of email addresses

Customize who receives failure notifications.

```php
add_filter('wpfmj_failure_notification_emails', function($emails) {
    return array(
        get_option('admin_email'),
        'developer@example.com',
        'support@example.com',
        'monitoring@example.com'
    );
});
```

**Use Cases:**
- **Development team**: Add developer emails
- **Support team**: Add support desk email
- **Monitoring**: Integrate with ticketing systems
- **Multiple admins**: Ensure redundancy

---

### 5. Disable Email Notifications

**Filter**: `wpfmj_disable_failure_notifications`  
**Default**: false (notifications enabled)  
**Type**: Boolean

Completely disable email notifications.

```php
add_filter('wpfmj_disable_failure_notifications', function($disabled) {
    return true; // Disable all emails
});
```

**When to disable:**
- Using external monitoring tools
- High-volume sites with frequent transient errors
- During development/testing

⚠️ **Note**: Errors are still logged in the database even when notifications are disabled.

---

### 6. Encryption Method

**Filter**: `wpfmj_encryption_method`  
**Default**: AES-256-CBC  
**Type**: String

Change the encryption algorithm for API credentials.

```php
add_filter('wpfmj_encryption_method', function($method) {
    return 'AES-256-GCM'; // More modern algorithm
});
```

**Available Methods:**
- `AES-256-CBC` (default, widely compatible)
- `AES-256-GCM` (modern, authenticated encryption)
- `AES-192-CBC`
- See `openssl_get_cipher_methods()` for full list

⚠️ **CRITICAL WARNING**: 
- **Only change BEFORE storing any credentials**
- Changing after credentials are stored will make them unreadable
- Requires re-entering all API keys if changed later
- Test thoroughly after changing

---

### 7. Debug Mode

**Filter**: `wpfmj_debug_mode`  
**Default**: false  
**Type**: Boolean

Enable verbose logging for troubleshooting.

```php
add_filter('wpfmj_debug_mode', function($debug) {
    return true; // Enable debug logging
});
```

**What gets logged:**
- API request details
- Retry attempts with timestamps
- Decryption operations
- Rate limit hits
- Form processing steps

**Important**: 
- Only enable when troubleshooting
- Logs may contain sensitive information
- Disable in production unless necessary
- Check `wp-content/debug.log`

---

### 8. Cleanup Cron Schedule

**Filter**: `wpfmj_cleanup_schedule`  
**Default**: weekly  
**Type**: String

Change how often error log cleanup runs.

```php
add_filter('wpfmj_cleanup_schedule', function($schedule) {
    return 'daily'; // Clean up more frequently
});
```

**Available Schedules:**
- `hourly` - Every hour
- `twicedaily` - Twice per day
- `daily` - Once per day
- `weekly` - Once per week (default)

**Considerations:**
- High-volume sites: Use `daily` or `twicedaily`
- Low-volume sites: `weekly` is sufficient
- More frequent = less database bloat

---

## Advanced Configuration Examples

### Example 1: High-Traffic Site

```php
<?php
// wpfmj-config.php for high-traffic e-commerce site

// Aggressive cleanup to manage database size
add_filter('wpfmj_error_log_retention_days', function($days) {
    return 30; // Only 30 days
});

// Higher rate limit for busy periods
add_filter('wpfmj_api_rate_limit', function($limit) {
    return 120;
});

// More frequent cleanup
add_filter('wpfmj_cleanup_schedule', function($schedule) {
    return 'daily';
});

// Multiple notification recipients
add_filter('wpfmj_failure_notification_emails', function($emails) {
    return array(
        'dev-team@example.com',
        'ops@example.com'
    );
});
```

### Example 2: Development Environment

```php
<?php
// wpfmj-config.php for staging/dev environment

// Disable email spam during testing
add_filter('wpfmj_disable_failure_notifications', function($disabled) {
    return true;
});

// Enable debug mode
add_filter('wpfmj_debug_mode', function($debug) {
    return true;
});

// Lower retry attempts for faster testing
add_filter('wpfmj_max_retry_attempts', function($attempts) {
    return 1; // Fail fast
});
```

### Example 3: Enterprise Setup

```php
<?php
// wpfmj-config.php for enterprise with compliance requirements

// Extended retention for audit compliance
add_filter('wpfmj_error_log_retention_days', function($days) {
    return 365; // 1 year
});

// Maximum reliability
add_filter('wpfmj_max_retry_attempts', function($attempts) {
    return 5;
});

// Security team notifications
add_filter('wpfmj_failure_notification_emails', function($emails) {
    return array(
        'security@example.com',
        'compliance@example.com',
        'it-ops@example.com'
    );
});

// Use modern encryption
add_filter('wpfmj_encryption_method', function($method) {
    return 'AES-256-GCM';
});
```

### Example 4: Minimal Configuration

```php
<?php
// wpfmj-config.php for simple site

// Just increase error retention slightly
add_filter('wpfmj_error_log_retention_days', function($days) {
    return 120; // 4 months
});
```

---

## Environment-Specific Configuration

You can use environment variables or constants for different environments:

```php
<?php
// wpfmj-config.php with environment detection

// Detect environment
$is_dev = (defined('WP_DEBUG') && WP_DEBUG === true);
$is_staging = (strpos($_SERVER['HTTP_HOST'], 'staging') !== false);

if ($is_dev) {
    // Development settings
    add_filter('wpfmj_disable_failure_notifications', '__return_true');
    add_filter('wpfmj_debug_mode', '__return_true');
    add_filter('wpfmj_max_retry_attempts', function() { return 1; });
    
} elseif ($is_staging) {
    // Staging settings
    add_filter('wpfmj_error_log_retention_days', function() { return 30; });
    add_filter('wpfmj_failure_notification_emails', function() {
        return array('staging-alerts@example.com');
    });
    
} else {
    // Production settings
    add_filter('wpfmj_error_log_retention_days', function() { return 90; });
    add_filter('wpfmj_api_rate_limit', function() { return 120; });
    add_filter('wpfmj_failure_notification_emails', function() {
        return array(
            'ops@example.com',
            'monitoring@example.com'
        );
    });
}
```

---

## Monitoring Your Configuration

### Check Current Settings

Add this to a test plugin or theme's functions.php temporarily:

```php
add_action('admin_init', function() {
    if (current_user_can('manage_options') && isset($_GET['wpfmj_check_config'])) {
        echo '<pre>';
        echo 'Error Retention: ' . apply_filters('wpfmj_error_log_retention_days', 90) . " days\n";
        echo 'API Rate Limit: ' . apply_filters('wpfmj_api_rate_limit', 60) . " req/min\n";
        echo 'Max Retries: ' . apply_filters('wpfmj_max_retry_attempts', 3) . " attempts\n";
        echo 'Debug Mode: ' . (apply_filters('wpfmj_debug_mode', false) ? 'ON' : 'OFF') . "\n";
        echo 'Notifications: ' . (apply_filters('wpfmj_disable_failure_notifications', false) ? 'DISABLED' : 'ENABLED') . "\n";
        echo '</pre>';
        exit;
    }
});
```

Visit: `yoursite.com/wp-admin/?wpfmj_check_config`

---

## Troubleshooting Configuration

### Configuration Not Loading

1. **Check file name**: Must be exactly `wpfmj-config.php`
2. **Check file location**: Must be in plugin root directory
3. **Check syntax**: Use PHP linter to verify no errors
4. **Check filters**: Ensure using `add_filter()` not `add_action()`

### Values Not Changing

1. **Clear caches**: Object cache, opcache, page cache
2. **Check filter priority**: Default priority is 10
3. **Verify filter name**: Must match exactly (case-sensitive)
4. **Test with simple value**: Try returning a hardcoded value first

### Debug Logging Not Working

1. **Enable WordPress debug logging**:
   ```php
   // In wp-config.php
   define('WP_DEBUG', true);
   define('WP_DEBUG_LOG', true);
   define('WP_DEBUG_DISPLAY', false);
   ```

2. **Check debug.log location**: `wp-content/debug.log`

3. **Verify debug mode filter is applied**

---

## Best Practices

### DO:
✅ Use `wpfmj-config.php` for customizations  
✅ Keep configuration in version control (except sensitive data)  
✅ Document your customizations  
✅ Test configuration changes in staging first  
✅ Use environment detection for different setups  
✅ Monitor logs after configuration changes  

### DON'T:
❌ Modify core plugin files directly  
❌ Store sensitive data in configuration file  
❌ Use extremely high rate limits without testing  
❌ Disable notifications without alternative monitoring  
❌ Change encryption method after storing credentials  
❌ Enable debug mode in production long-term  

---

## Performance Considerations

| Setting | Impact | Recommendation |
|---------|--------|----------------|
| Error Retention (Low) | Less DB storage | Good for high-volume |
| Error Retention (High) | More DB storage | Good for compliance |
| API Rate Limit (Low) | Slower processing | More reliable |
| API Rate Limit (High) | Faster processing | Monitor closely |
| Max Retries (Low) | Fast failure | Development |
| Max Retries (High) | Slow failure | Production |
| Cleanup (Frequent) | More CPU usage | High-volume sites |
| Cleanup (Infrequent) | Less CPU usage | Low-volume sites |

---

## Security Considerations

1. **Never commit sensitive data**: Use environment variables for secrets
2. **File permissions**: Set `wpfmj-config.php` to 644 or 600
3. **Encryption changes**: Only change before first use
4. **Debug mode**: Never leave enabled with sensitive operations
5. **Email recipients**: Ensure all recipients are trusted

---

## Getting Help

If you need assistance with configuration:

1. **Check debug logs**: Enable debug mode temporarily
2. **Test with defaults**: Remove config file to use defaults
3. **Verify syntax**: Use PHP linter on config file
4. **Review examples**: See examples in this guide
5. **Contact support**: Include configuration (without sensitive data)

---

## Version History

### 1.0.1
- Added configurable error retention period
- Added configurable API rate limiting
- Added configurable retry attempts
- Added configurable email notifications
- Added configurable encryption method
- Added debug mode
- Added cleanup schedule customization

---

**Last Updated**: October 16, 2025  
**Plugin Version**: 1.0.1+  
**Compatibility**: WordPress 5.8+, PHP 7.4+
