# Aegilock Transaction Guardian for WooCommerce v1.0.20

Advanced transaction security for WooCommerce with ML-powered order screening, real-time protection, and intelligent risk assessment.

## Latest Update v1.0.20 - Save Money on Payment Fees

### What's New
- **IMPROVED: Fraud checks now run BEFORE payment is charged** - Save money by blocking fraudulent orders before payment gateway fees are incurred
- **NEW: Automatic Refund System** - If payment is processed before fraud detection completes, the order is automatically refunded

### How It Works
The plugin uses a two-layer protection system:

**Best Case:** Checkout is blocked before payment
- Fraud detection runs during checkout validation
- High-risk orders are blocked completely
- No payment is processed
- Zero payment gateway fees

**Worst Case:** Payment is immediately refunded
- If payment gateway processes payment before fraud check completes
- Order is automatically refunded within seconds
- Minimal fees instead of full transaction costs
- Order status set to "cancelled"

### Why This Matters
When fraudulent orders are detected:
- Primary protection: Block checkout entirely (no fees)
- Backup protection: Immediate automatic refund (minimal fees)
- Either way: Significant cost savings for your shop
- Fraudsters cannot complete transactions

## Previous Update v1.0.16 - Email Blacklist Management

### New Features
- **Email Blacklist Management** - Block specific emails or entire domains with wildcard support
- **Exact Email Matching** - Block individual email addresses (spammer@example.com)
- **Domain-Wide Blocking** - Use wildcards to block entire domains (*@spam.com)
- **Advanced Pattern Matching** - Support for complex patterns (trouble.*@*)
- **Automatic 99% Fraud Score** - Blacklisted emails are instantly flagged as high-risk
- **Simple Management** - Easy-to-use textarea field in admin settings

### How It Works
The email blacklist provides multiple layers of protection:

```
# Block specific email
spammer@example.com

# Block entire domain
*@throwaway.com

# Block pattern
trouble.*@*
```

When a blacklisted email is detected:
1. Order automatically receives 99% fraud score
2. Triggers configured fraud protection actions
3. Logged in debug mode for tracking
4. Can trigger email alerts if enabled

## Previous Update v1.0.14 - Critical Fixes & Country-Level Fraud Analytics

### Critical Fixes
- **Fraud Risk Column Now Working** - Fixed display issue where fraud scores showed "-" instead of actual values
- **Proper WordPress.org Tracking** - Plugin now correctly tracked for active installation counts
- **Order Processing Fixed** - Multiple hooks ensure all orders (frontend, admin, CLI, API) are processed
- **Score Display Enhanced** - Fraud scores now display as percentages (45% instead of 0.45)

### New Features
- **Country Fraud Statistics** - Dashboard widget shows top 5 countries by fraud rate (last 30 days)
- **Color-Coded Risk Rates** - Green (<15%), Yellow (15-30%), Red (>30%) for instant insights
- **Enhanced Debug Logging** - Detailed logs for troubleshooting order processing issues
- **Auto-Repair System** - Automatic database integrity verification and repair

### Dashboard Analytics
The dashboard now includes a professional country-level fraud statistics table:
```
Country          | Orders | High Risk | Rate
Germany          | 234    | 12        | 5.1%  (Green)
United States    | 567    | 89        | 15.7% (Yellow)
China            | 123    | 45        | 36.6% (Red)
```

## Previous Major Update v1.0.12 - Complete Security & Architecture Overhaul

### New Enterprise Features
- **Review Queue System** - Professional manual review interface for flagged orders
- **Webhook System** - Real-time notifications with HMAC signature security
- **PHPUnit Test Suite** - Comprehensive 80+ tests for enterprise reliability
- **Enhanced Fraud Detection** - Advanced behavioral and geolocation analysis

### Complete Professional Architecture
- **Unified Order Processing** - Merged redundant classes for better maintainability
- **Performance Optimization** - 5x faster queries with optimized pagination
- **Professional Testing** - Health checks with PHPUnit integration
- **Enterprise Security** - CSRF protection and comprehensive error handling

### Security Fixes
- **Fixed all SQL injection vulnerabilities** with proper prepared statements
- **Comprehensive input sanitization** for all user data
- **Nonce verification** for all admin actions
- **Capability checks** throughout the plugin

### Architecture Refactoring
- **Split monolithic 931-line class** into specialized components:
  - `Aegilock_Database_Handler` - All database operations with transaction support
  - `Aegilock_Fraud_Calculator` - Fraud detection and risk assessment
  - `Aegilock_Order_Processor` - Order processing and actions
  - `Aegilock_Admin_Interface` - Secure admin functionality
  - `Aegilock_Testing` - Plugin health checks

### Performance Improvements
- **Removed self-healing functions** that caused performance issues
- **Optimized database queries** from 200 to 20 items with pagination
- **Eliminated duplicate code** throughout the plugin
- **Proper WordPress/WooCommerce hook integration**

### International Support
- **Removed Euro-specific validations** - now supports all currencies
- **Currency-neutral fraud detection** algorithms
- **Internationalization ready**

### Database Improvements
- **Proper database transactions** with rollback on errors
- **Comprehensive error handling** with try-catch blocks
- **Graceful error recovery** mechanisms

### What's New

#### Professional Class Architecture v1.0.12
```
├── class-aegilock-wc-database-handler.php    # Database operations & transactions
├── class-aegilock-wc-fraud-calculator.php    # Enhanced fraud detection algorithms
├── class-aegilock-wc-order-processor.php     # Unified order processing & actions
├── class-aegilock-wc-admin-interface.php     # Secure admin interface & settings
├── class-aegilock-wc-review-queue.php        # Manual review system (NEW)
├── class-aegilock-wc-webhook-system.php      # Webhook notifications (NEW)
└── class-aegilock-wc-testing.php             # Health checks & PHPUnit integration
```

#### Enterprise Features v1.0.12
- **Review Queue**: Professional manual order review with bulk actions
- **Webhook System**: Real-time event notifications with HMAC security
- **PHPUnit Tests**: 80+ comprehensive tests for enterprise reliability
- **Enhanced Detection**: Behavioral patterns, geolocation, timing analysis
- **Performance**: Optimized queries with 10-item pagination (was 50)
- **Security**: CSRF protection on all AJAX endpoints

#### Security Improvements
- SQL injection protection
- XSS prevention
- CSRF protection with nonces
- Input validation & sanitization
- Capability-based access control

#### Performance Optimizations
- Database query optimization
- Pagination support
- Efficient memory usage
- Reduced server load

## Installation

1. Upload the plugin files to `/wp-content/plugins/aegilock-transaction-guardian-for-woocommerce/`
2. Activate the plugin through the WordPress plugins screen
3. Navigate to WooCommerce → Settings → Aegilock to configure

## Configuration

### Basic Settings
- **Enable Fraud Detection**: Turn on/off the fraud detection system
- **Test Mode**: Enable for testing (orders won't be blocked)
- **Fraud Threshold**: Set the risk threshold (0.1 - 1.0)

### Actions
- **Block High Risk Orders**: Automatically set high-risk orders to "failed"
- **Hold Medium Risk Orders**: Set medium-risk orders to "on-hold"
- **Email Alerts**: Receive notifications for flagged orders

### Blacklist Management
- **Email Blacklist**: Block specific emails or entire domains with wildcard support
  - Exact matches: `spammer@example.com`
  - Domain wildcards: `*@spam.com`
  - Pattern matching: `trouble.*@*`
- **Country Blacklist**: Orders from these countries are flagged

### Other Controls
- **Order Amount Limits**: Set minimum/maximum order values

## Testing

The plugin includes a built-in testing system:

```php
// Run basic health checks
$results = Aegilock_Testing::run_basic_tests();

// Display test results in admin
Aegilock_Testing::display_test_results();
```

## Developer API

### Database Operations
```php
$db_handler = Aegilock_Database_Handler::instance();
$db_handler->log_fraud_attempt($order_id, $score, $factors, $action);
```

### Fraud Calculation
```php
$calculator = Aegilock_Fraud_Calculator::instance();
$result = $calculator->calculate_fraud_score($order);
```

### Order Processing
```php
$processor = Aegilock_Order_Processor::instance();
$processor->process_new_order($order_id);
```

## Dashboard

Access the security dashboard at **WooCommerce → Aegilock Security**:
- Today's security statistics
- Recent fraud logs
- Risk factor analysis
- Order details with fraud scores

## Security Features

### Fraud Detection
- **Email blacklist management** - Block specific emails or domains with wildcard support
- **Email pattern analysis** - Detects suspicious email addresses
- **Country risk assessment** - Geographic fraud indicators
- **Order amount analysis** - Unusual purchase patterns
- **Customer history review** - Trust level calculation
- **Payment method validation** - Risk-based on payment types

### Trusted Customer System
- **Multi-factor validation** combining:
  - Account age (minimum 90 days)
  - Average order value
  - Order frequency limits
  - Purchase history analysis

## Migration from Previous Versions

Version 1.0.12 maintains backward compatibility with previous versions. The new architecture runs alongside legacy code to ensure smooth operation.

### Database Migration
- Existing fraud logs are preserved
- Statistics continue from previous versions
- Settings are automatically migrated

## Changelog

### v1.0.16 - Email Blacklist Management
- **NEW**: Email blacklist feature with wildcard support
- **NEW**: Block specific emails or entire domains
- **NEW**: Support for exact email matching and wildcard patterns (*@domain.com)
- **NEW**: Blacklisted emails automatically receive 99% fraud score
- **IMPROVED**: Admin settings interface with textarea field for blocked emails
- **ENHANCED**: Fraud Calculator now checks email blacklist first for instant detection

### v1.0.12 (2024-12-21) - FINAL CLEANED VERSION
- **MAJOR SECURITY**: Fixed all SQL injection vulnerabilities with prepared statements
- **ARCHITECTURE**: Complete code refactoring into specialized classes - no redundancy
- **ENTERPRISE FEATURES**: Review Queue System for manual order review and approval
- **WEBHOOK SYSTEM**: Simplified webhook system (50 lines instead of 610 lines)
- **TESTING SUITE**: Complete PHPUnit test coverage with 80+ comprehensive tests
- **ENHANCED DETECTION**: Behavioral pattern analysis, geolocation risk, timing patterns
- **UNIFIED ARCHITECTURE**: All redundant classes removed - single responsibility per class
- **PERFORMANCE**: Optimized pagination from 50 to 10 items (5x faster response times)
- **CODE CLEANUP**: Removed all dead references and tote code
- **DEAD REFERENCE FIX**: Fixed Aegilock_WC_Orders reference that didn't exist
- **SIMPLIFIED WEBHOOKS**: Basic webhook functionality without complexity overhead
- **PROFESSIONAL TESTING**: Health check system with PHPUnit integration
- **DATABASE**: Extended schema with review tracking
- **SECURITY**: CSRF protection for all AJAX endpoints with nonce verification
- **INTERNATIONAL**: Removed Euro-specific validations for global compatibility
- **SECURITY**: Added comprehensive security measures
- **DATABASE**: Implemented proper transaction support
- **TESTING**: Added health check system

## Requirements

- **WordPress**: 5.8 or higher
- **WooCommerce**: 6.0 or higher
- **PHP**: 7.4 or higher
- **Database**: MySQL 5.6 or higher

## Support

For support and documentation, visit [aegilock.de](https://aegilock.de)

## License

This plugin is licensed under GPL v2 or later.

---

**Aegilock Transaction Guardian** - Protecting your WooCommerce store from fraud since 2024.