# Sentinel - WordPress Activity Logging Plugin

A comprehensive, extensible activity logging system for WordPress that tracks user actions, system events, and custom activities with a beautiful dashboard interface.

## 🚀 Features

### Core Functionality
- **Automatic WordPress Event Logging**: Tracks login/logout, user registration, profile updates, post actions, comments, and plugin activation/deactivation
- **Comprehensive Data Capture**: IP addresses, user agents, URLs, and custom data
- **Priority System**: Info, warning, error, and critical priority levels
- **Category Organization**: Organize events by categories (authentication, content, social, etc.)

### Dashboard & Analytics
- **Real-time Dashboard**: Beautiful charts and statistics
- **Activity Timeline**: 7-day activity visualization
- **Event Distribution**: Doughnut chart showing event types
- **Top Users**: Most active users tracking
- **Recent Activity Feed**: Live activity stream
- **System Information**: Database size, retention policies, and system health

### Admin Features
- **Advanced Log Viewer**: Filter by event type, user, priority, and date range
- **CSV Export**: Export all logs for external analysis
- **Log Cleanup**: Automatic cleanup of old logs (30-day retention)
- **Search & Filter**: Powerful search capabilities
- **Pagination**: Efficient handling of large log volumes

### Developer-Friendly
- **Public API**: Simple functions for integrations
- **Extensible Architecture**: Modular design for easy customization
- **WordPress Standards**: Follows WordPress coding standards and best practices

## 📦 Installation

1. Upload the `sentinel` folder to your `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress
3. Access the dashboard via 'Sentinel' in the admin menu

## 🔧 Usage

### Basic Logging

```php
// Log a simple event
sentinel_log_event('user_action', array('action' => 'button_clicked'));

// Log with custom data
sentinel_log_event('bounty_uploaded', array(
    'trophy_name' => 'Platinum Trophy',
    'bounty_value' => 500,
    'auto_approved' => true
));
```

### Registering Custom Events

> **Custom event registration is available in Sentinel Pro.**

### Advanced Usage

```php
// Log with specific user and priority
sentinel_log_event('important_action', array(
    'user_id' => 123,
    'priority' => 'warning',
    'data' => array(
        'action' => 'admin_login_attempt',
        'ip_address' => '192.168.1.1'
    )
));
```

## 🎯 JPSNT Integration

Sentinel is designed to work seamlessly with JPSNT (JustPSNTrophies) and can log:

- **Bounty Activities**: Uploads, approvals, rejections
- **User Interactions**: Follows, unfollows, reactions
- **Game Management**: Collection additions/removals
- **Difficulty Ratings**: User-submitted ratings
- **Social Features**: Comments, reactions, interactions

### Example JPSNT Events

```php
// Log bounty upload
sentinel_log_event('bounty_uploaded', array(
    'trophy_name' => get_the_title($trophy_id),
    'bounty_value' => $bounty_value,
    'auto_approved' => $auto_approved
));

// Log user follow
sentinel_log_event('user_followed', array(
    'follower_id' => $follower_id,
    'followed_id' => $followed_id
));

// Log difficulty rating
sentinel_log_event('difficulty_rated', array(
    'trophy_id' => $trophy_id,
    'rating' => $rating,
    'user_id' => get_current_user_id()
));
```

## 📊 Dashboard Features

### Overview Statistics
- **Today's Logs**: Number of events logged today
- **Active Users**: Unique users with activity today
- **Top Event**: Most frequent event type today
- **Database Size**: Current log table size

### Charts & Visualizations
- **Activity Timeline**: Line chart showing 7-day activity trends
- **Event Distribution**: Doughnut chart of event types
- **Interactive Elements**: Hover tooltips and responsive design

### Quick Actions
- **View All Logs**: Access the detailed log viewer
- **Export Logs**: Download CSV export of all logs
- **Clear Old Logs**: Remove logs older than 30 days
- **Generate Test Data**: Create sample data for testing

## 🔍 Log Viewer

### Filtering Options
- **Event Type**: Filter by specific event keys
- **User**: Filter by user ID or username
- **Priority**: Filter by priority level
- **Date Range**: Filter by creation date
- **Category**: Filter by event category

### Display Features
- **User-friendly Messages**: Human-readable activity descriptions
- **Context Data**: Expandable JSON data for each log entry
- **Pagination**: Efficient navigation through large datasets
- **Sorting**: Sort by any column

## 🛠️ API Reference

### Core Functions

#### `sentinel_log_event($event_key, $data = array(), $user_id = null)`
Log an event with optional data and user ID.

**Parameters:**
- `$event_key` (string): The event identifier
- `$data` (array): Optional data to store with the event
- `$user_id` (int): Optional user ID (defaults to current user)

**Returns:** `bool` - Success status

#### `sentinel_register_event($event_key, $config = array())`
> **This function is available in Sentinel Pro.**

**Parameters:**
- `$event_key` (string): The event identifier
- `$config` (array): Event configuration
  - `label` (string): Human-readable label
  - `category` (string): Event category
  - `priority` (string): Default priority level
  - `description` (string): Event description

**Returns:** `bool` - Success status

### Database Schema

The plugin creates a `wp_sentinel_logs` table with the following structure:

```sql
CREATE TABLE wp_sentinel_logs (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    event_key varchar(100) NOT NULL,
    category varchar(50) DEFAULT 'general',
    priority varchar(20) DEFAULT 'info',
    user_id bigint(20) DEFAULT 0,
    ip_address varchar(45) DEFAULT NULL,
    user_agent text DEFAULT NULL,
    url text DEFAULT NULL,
    data longtext DEFAULT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY event_key (event_key),
    KEY user_id (user_id),
    KEY created_at (created_at),
    KEY priority (priority)
);
```

## 🔧 Configuration

### Retention Policy
By default, logs are retained for 30 days. This can be modified in the admin interface or by editing the cleanup function.

### Priority Levels
- **info**: General information (default)
- **warning**: Warning-level events
- **error**: Error conditions
- **critical**: Critical system events

### Categories
- **authentication**: Login/logout events
- **content**: Post and page actions
- **social**: Comments and interactions
- **bounty**: Trophy bounty activities
- **collection**: Game collection management
- **rating**: Difficulty and rating events
- **system**: Plugin and system events
- **custom**: Custom registered events

## 🚀 Performance

### Optimizations
- **Indexed Queries**: Database indexes on frequently queried columns
- **Pagination**: Efficient handling of large datasets
- **Caching**: WordPress object caching integration
- **Cleanup**: Automatic removal of old logs

### Database Impact
- **Minimal Overhead**: Lightweight logging with minimal performance impact
- **Efficient Storage**: JSON data storage for flexibility
- **Automatic Cleanup**: Prevents database bloat

## 🔒 Security

### Data Protection
- **Input Sanitization**: All user inputs are properly sanitized
- **SQL Preparation**: All database queries use prepared statements
- **Permission Checks**: Admin-only access to sensitive functions
- **Nonce Verification**: CSRF protection for all admin actions

### Privacy Considerations
- **IP Address Logging**: Configurable IP address capture
- **User Agent Logging**: Optional user agent storage
- **Data Retention**: Configurable retention policies
- **GDPR Compliance**: Easy data export and deletion

## 🐛 Troubleshooting

### Common Issues

**Plugin not activating:**
- Check PHP version (requires 7.4+)
- Verify WordPress version (requires 5.0+)
- Check for plugin conflicts

**Dashboard not loading:**
- Verify admin permissions
- Check for JavaScript errors
- Ensure Chart.js is loading

**Logs not appearing:**
- Check database permissions
- Verify table creation
- Check for PHP errors

### Debug Mode

Enable WordPress debug mode to see detailed error messages:

```php
// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
```

## 📈 Future Enhancements

### Planned Features
- **Real-time Notifications**: WebSocket-based live updates
- **Advanced Analytics**: More detailed reporting and insights
- **API Endpoints**: REST API for external integrations
- **Email Alerts**: Configurable email notifications
- **Custom Dashboards**: User-defined dashboard layouts
- **Data Visualization**: More chart types and visualizations

### Extensibility
- **Hook System**: WordPress action and filter hooks
- **Event Listeners**: Custom event processing (Pro)
- **Export Formats**: Additional export formats (JSON, XML)
- **Third-party Integrations**: Slack, Discord, etc. (Pro)

## 🤝 Contributing

### Development Setup
1. Clone the repository
2. Set up a local WordPress development environment
3. Activate the plugin
4. Make your changes
5. Test thoroughly
6. Submit a pull request

### Coding Standards
- Follow WordPress coding standards
- Use proper PHPDoc comments
- Include unit tests for new features
- Maintain backward compatibility

## 📄 License

This plugin is licensed under the GPL v2 or later.

## 🙏 Acknowledgments

- Built for the JPSNT community
- Inspired by modern logging systems
- Uses Chart.js for data visualization
- Follows WordPress best practices

---

**Sentinel** - Your WordPress activity guardian, keeping watch over every action and interaction on your site. 🛡️ 