# Audit Logging System Documentation

## Overview

The Audit Logging System provides comprehensive change tracking for the HR module and other parts of the application. It automatically logs all create, update, and delete operations with detailed information about what changed, who made the change, and when.

## Features

### 🔍 **Automatic Change Tracking**
- Tracks all CRUD operations (Create, Read, Update, Delete)
- Records field-level changes with old and new values
- Captures user information, IP address, and request details
- Supports soft deletes and restoration

### 📊 **Advanced Filtering & Search**
- Filter by event type, model, user, date range
- Search across notes, IP addresses, and URLs
- Tag-based filtering for better organization
- Pagination support for large datasets

### 📈 **Statistics & Analytics**
- Visual charts showing event distribution
- Model activity tracking
- User activity analysis
- Daily activity trends
- Export capabilities (CSV, XLSX, PDF)

### 🛡️ **Security & Compliance**
- Complete audit trail for compliance
- IP address tracking
- User agent logging
- Request method and URL capture
- Tamper-evident logging

## Architecture

### Core Components

1. **AuditLog Model** (`app/Models/AuditLog.php`)
   - Stores audit log entries
   - Provides relationships and query scopes
   - Includes helper methods for data access

2. **Auditable Trait** (`app/Traits/Auditable.php`)
   - Automatically logs model changes
   - Configurable via model events
   - Supports custom tags and notes

3. **AuditLogController** (`app/Http/Controllers/AuditLogController.php`)
   - Handles audit log viewing and management
   - Provides filtering and export functionality
   - Includes statistics generation

4. **Database Schema** (`audit_logs` table)
   - Stores comprehensive change information
   - Optimized with proper indexes
   - Supports JSON fields for flexible data storage

### Database Schema

```sql
CREATE TABLE audit_logs (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    auditable_type VARCHAR(255) NOT NULL,      -- Model class name
    auditable_id BIGINT NOT NULL,              -- Model ID
    event VARCHAR(255) NOT NULL,               -- created, updated, deleted, restored
    old_values JSON NULL,                      -- Previous values
    new_values JSON NULL,                      -- New values
    changed_fields JSON NULL,                  -- Fields that changed
    user_type VARCHAR(255) NULL,               -- User model type
    user_id BIGINT NULL,                       -- User ID
    ip_address VARCHAR(45) NULL,               -- IP address
    user_agent TEXT NULL,                      -- Browser info
    url VARCHAR(255) NULL,                     -- Request URL
    method VARCHAR(10) NULL,                   -- HTTP method
    tags JSON NULL,                            -- Custom tags
    notes TEXT NULL,                           -- Additional notes
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    
    -- Indexes for performance
    INDEX idx_auditable (auditable_type, auditable_id),
    INDEX idx_user (user_type, user_id),
    INDEX idx_event (event),
    INDEX idx_created_at (created_at),
    INDEX idx_auditable_event (auditable_type, event),
    
    -- Foreign key
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
);
```

## Usage

### Enabling Audit Logging

To enable audit logging for a model, simply add the `Auditable` trait:

```php
<?php

namespace Modules\HR\Entities;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use Auditable;
    
    // ... rest of your model
}
```

### Configuration

Configure audit logging in `config/audit.php`:

```php
<?php

return [
    'enabled' => env('AUDIT_LOGGING_ENABLED', true),
    'disabled' => env('AUDIT_LOGGING_DISABLED', false),
    
    // Skip certain events
    'skip_events' => [
        // 'created',
        // 'updated',
        // 'deleted',
    ],
    
    // Skip certain models
    'skip_models' => [
        // App\Models\AuditLog::class,
    ],
    
    // Skip certain fields
    'skip_fields' => [
        'created_at',
        'updated_at',
        'deleted_at',
        'remember_token',
        'password',
    ],
    
    // Retention policy (days)
    'retention_days' => env('AUDIT_RETENTION_DAYS', 365),
    
    // UI configuration
    'ui' => [
        'enabled' => env('AUDIT_UI_ENABLED', true),
        'route_prefix' => 'audit-logs',
        'per_page' => 25,
    ],
];
```

### Environment Variables

Add these to your `.env` file:

```env
# Audit Logging Configuration
AUDIT_LOGGING_ENABLED=true
AUDIT_LOGGING_DISABLED=false
AUDIT_RETENTION_DAYS=365
AUDIT_UI_ENABLED=true
AUDIT_EXPORT_ENABLED=true
```

## API Endpoints

### View Audit Logs
```
GET /audit-logs
GET /audit-logs/dashboard
GET /audit-logs/{auditLog}
GET /audit-logs/statistics
```

### Filtering Parameters
- `event` - Filter by event type (created, updated, deleted)
- `model_type` - Filter by model class
- `user_id` - Filter by user
- `date_from` - Start date filter
- `date_to` - End date filter
- `search` - Search in notes, IP, URL
- `per_page` - Results per page (25, 50, 100)

### Export
```
GET /audit-logs/export?format=csv
GET /audit-logs/export?format=xlsx
GET /audit-logs/export?format=pdf
```

### Cleanup
```
POST /audit-logs/cleanup
```

## Views & UI

### Main Views

1. **Dashboard** (`/audit-logs/dashboard`)
   - Overview of the audit logging system
   - Recent activity display
   - Quick action buttons

2. **Index** (`/audit-logs`)
   - Complete audit log listing
   - Advanced filtering options
   - Export functionality

3. **Show** (`/audit-logs/{id}`)
   - Detailed view of a single audit log
   - Change comparison (before/after)
   - Request information

4. **Statistics** (`/audit-logs/statistics`)
   - Visual charts and analytics
   - Event distribution
   - User activity analysis

### Navigation

Add to your navigation menu:

```html
<li class="nav-item">
    <a class="nav-link" href="{{ route('audit-logs.dashboard') }}">
        <i class="fas fa-history"></i>
        Audit Logs
    </a>
</li>
```

## Querying Audit Logs

### Using the Model

```php
use App\Models\AuditLog;

// Get all audit logs
$logs = AuditLog::all();

// Filter by event
$createdLogs = AuditLog::event('created')->get();

// Filter by model
$employeeLogs = AuditLog::forModel('Modules\HR\Entities\Employee')->get();

// Filter by user
$userLogs = AuditLog::byUser(1)->get();

// Date range
$recentLogs = AuditLog::dateRange('2024-01-01', '2024-12-31')->get();

// Recent logs
$recentLogs = AuditLog::recent(7)->get(); // Last 7 days
```

### Using Relationships

```php
use Modules\HR\Entities\Employee;

$employee = Employee::find(1);

// Get audit logs for this employee
$logs = $employee->auditLogs;

// Get recent logs
$recentLogs = $employee->recentAuditLogs(10);

// Get logs for specific event
$updateLogs = $employee->auditLogsFor('updated');

// Get modification history summary
$history = $employee->getModificationHistory();
```

## Performance Considerations

### Database Indexes

The audit logs table includes optimized indexes:
- `idx_auditable` - For model-specific queries
- `idx_user` - For user-specific queries
- `idx_event` - For event filtering
- `idx_created_at` - For date range queries
- `idx_auditable_event` - For combined queries

### Retention Policy

Configure automatic cleanup:

```php
// In your scheduler or cron job
php artisan audit:cleanup
```

Or manually:

```php
use App\Models\AuditLog;

$retentionDays = config('audit.retention_days', 365);
$cutoffDate = Carbon::now()->subDays($retentionDays);

$deleted = AuditLog::where('created_at', '<', $cutoffDate)->delete();
```

### Memory Optimization

For large datasets:
- Use pagination
- Implement chunked processing
- Consider archiving old logs
- Use database-level filtering

## Security Considerations

### Access Control

Ensure proper middleware for audit log routes:

```php
Route::middleware(['auth', 'admin'])->group(function () {
    Route::prefix('audit-logs')->name('audit-logs.')->group(function () {
        // Audit log routes
    });
});
```

### Data Privacy

- Consider PII (Personally Identifiable Information) in logs
- Implement data anonymization if required
- Ensure compliance with GDPR/privacy regulations
- Use encryption for sensitive audit data

### Log Integrity

- Store logs in read-only database
- Implement log verification mechanisms
- Consider digital signatures for critical logs
- Regular backup and archival

## Troubleshooting

### Common Issues

1. **Memory Exhaustion**
   - Check for infinite recursion in trait methods
   - Verify model relationships
   - Use chunked processing for large datasets

2. **Missing Logs**
   - Verify trait is properly added to models
   - Check configuration settings
   - Ensure database constraints are met

3. **Performance Issues**
   - Check database indexes
   - Optimize queries with proper filtering
   - Consider archiving old data

### Debug Mode

Enable debug logging:

```php
// In config/audit.php
'debug' => env('AUDIT_DEBUG', false),
```

### Testing

Test audit logging:

```php
// Create a test model
$employee = new Employee();
$employee->first_name = 'Test';
$employee->save();

// Check audit log
$log = AuditLog::where('auditable_type', 'Modules\HR\Entities\Employee')
               ->where('auditable_id', $employee->id)
               ->where('event', 'created')
               ->first();

assert($log !== null, 'Audit log should be created');
```

## Integration Examples

### Custom Tags

Add custom tags to audit logs:

```php
class Employee extends Model
{
    use Auditable;
    
    protected function getAuditTags(): array
    {
        return [
            'department' => $this->department->name ?? 'Unknown',
            'branch' => $this->branch->name ?? 'Unknown',
        ];
    }
}
```

### Custom Notes

Add contextual notes:

```php
class Employee extends Model
{
    use Auditable;
    
    protected function getAuditNotes(string $event): ?string
    {
        if ($event === 'updated') {
            return "Employee profile updated via HR portal";
        }
        
        return null;
    }
}
```

### Event Listeners

Custom event handling:

```php
// In AppServiceProvider
public function boot()
{
    Employee::updated(function ($employee) {
        // Custom logic after employee update
        if ($employee->wasChanged('salary')) {
            // Send notification, etc.
        }
    });
}
```

## Future Enhancements

### Planned Features

1. **Real-time Notifications**
   - WebSocket integration
   - Email alerts for critical changes
   - Dashboard notifications

2. **Advanced Analytics**
   - Machine learning insights
   - Anomaly detection
   - Predictive analytics

3. **Integration APIs**
   - REST API endpoints
   - Webhook support
   - Third-party integrations

4. **Enhanced Security**
   - Digital signatures
   - Blockchain integration
   - Advanced encryption

### Contributing

To contribute to the audit logging system:

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Update documentation
5. Submit a pull request

## Support

For support and questions:

- Check the troubleshooting section
- Review the configuration options
- Test with sample data
- Contact the development team

---

**Note**: This audit logging system is designed to be comprehensive yet lightweight. It provides essential change tracking capabilities while maintaining good performance and security practices.

