# Activity Logs - Quick Reference Guide

## For Developers: How to Use Activity Logging

### Quick Start

1. **Add trait to your controller:**
```php
use App\Traits\LogsActivity;

class YourController extends Controller
{
    use LogsActivity;
}
```

2. **Log an activity:**
```php
$this->logPrescriptionActivity(
    'approved',
    'John Smith',
    'Amoxicillin 500mg',
    'RX #9425',
    'approved'
);
```

## Common Use Cases

### 1. Prescription Approved/Sent
```php
$this->logPrescriptionActivity(
    'sent',                          // Action: sent, approved, declined, cancelled, pending
    $patientName,                    // Full patient name
    $medicationName,                 // Medication with dosage
    $prescriptionId,                 // Reference number (RX #xxxx)
    'approved'                       // Status
);
```

### 2. Lab Results Reviewed
```php
$this->logLabReviewActivity(
    $patientName,                    // Full patient name
    'Complete Blood Count',          // Test type
    'LAB #8821',                     // Lab reference number
    'All values normal'              // Results summary (optional)
);
```

### 3. Intake Form Updated
```php
$this->logIntakeUpdateActivity(
    $patientName,                    // Full patient name
    'INT #4512',                     // Intake form reference
    'Updated allergy information'    // What was updated
);
```

### 4. Consultation Completed
```php
$this->logConsultationActivity(
    $patientName,                    // Full patient name
    'CONS #2201',                    // Consultation reference
    'Virtual'                        // Consultation type
);
```

### 5. Custom Activity
```php
$this->logActivity(
    'custom_action',                 // Action type
    'Custom description',            // Human-readable description
    $patientName,                    // Full patient name
    'REF #1234',                     // Reference number (optional)
    'Additional details',            // Details (optional)
    'Dr. Smith',                     // Performed by (optional, auto-detected)
    'completed'                      // Status (optional)
);
```

## Action Types Reference

| Action Type | When to Use | Example |
|------------|-------------|---------|
| `prescription_sent` | Prescription submitted to pharmacy | Prescription sent to CVS |
| `prescription_approved` | Prescription approved by doctor | Prescription approved |
| `prescription_pending` | Prescription awaiting review | Prescription pending review |
| `prescription_declined` | Prescription denied | Prescription request declined |
| `prescription_cancelled` | Prescription cancelled | Prescription cancelled |
| `lab_reviewed` | Lab results reviewed | Lab Results Reviewed |
| `intake_updated` | Intake form modified | Intake Form Updated |
| `consultation_completed` | Consultation finished | Virtual consultation completed |
| `info_requested` | More info needed | Additional info requested |

## Status Types Reference

| Status | Badge Color | When to Use |
|--------|-------------|-------------|
| `approved` | Green | Prescription approved, action successful |
| `pending` | Yellow | Awaiting review/approval |
| `completed` | Blue | Task finished (consultations, reviews) |
| `cancelled` | Red | Action cancelled/declined |

## Method Parameters

### `logActivity()` - Generic Activity Logging
```php
protected function logActivity(
    string $actionType,        // Required: Type of action
    string $description,       // Required: Human-readable description
    string $patientName,       // Required: Patient's full name
    ?string $referenceNumber,  // Optional: Reference ID (RX #, LAB #, etc.)
    ?string $details,          // Optional: Additional details
    ?string $performedBy,      // Optional: Staff name (auto-detected from session)
    ?string $status            // Optional: Status badge
): ActivityLog
```

### `logPrescriptionActivity()` - Simplified Prescription Logging
```php
protected function logPrescriptionActivity(
    string $action,            // sent, approved, declined, cancelled, pending
    string $patientName,       // Patient's full name
    string $medication,        // Medication name (e.g., "Amoxicillin 500mg")
    string $referenceNumber,   // Prescription ID (e.g., "RX #9425")
    string $status = 'approved' // Status (default: approved)
): ActivityLog
```

### `logLabReviewActivity()` - Lab Review Logging
```php
protected function logLabReviewActivity(
    string $patientName,       // Patient's full name
    string $testType,          // Type of test (e.g., "Complete Blood Count")
    string $referenceNumber,   // Lab reference (e.g., "LAB #8821")
    string $results = null     // Optional: Results summary
): ActivityLog
```

## Code Examples

### Example 1: Logging in Controller Action
```php
public function approveRequest(Request $request, $patientId)
{
    // Process the approval
    $prescription = Prescription::create([...]);
    
    // Log the activity
    $this->logPrescriptionActivity(
        'approved',
        $request->patient_name,
        $request->medication,
        $prescription->erx_id,
        'approved'
    );
    
    return redirect()->back()->with('success', 'Approved!');
}
```

### Example 2: Logging After External API Call
```php
public function sendToPharmacy($prescription)
{
    // Send to pharmacy API
    $response = PharmacyAPI::send($prescription);
    
    if ($response->success) {
        // Log successful send
        $this->logPrescriptionActivity(
            'sent',
            $prescription->patient_name,
            $prescription->medication,
            $prescription->erx_id,
            'approved'
        );
    }
}
```

### Example 3: Logging Multiple Actions
```php
public function processPatient(Request $request, $id)
{
    $patient = Patient::find($id);
    
    if ($request->action === 'approve') {
        // Approve and log
        $this->logPrescriptionActivity(...);
        
    } elseif ($request->action === 'request_info') {
        // Request more info and log
        $this->logActivity(
            'info_requested',
            'Additional information requested',
            $patient->full_name,
            $patient->id,
            'Request for more details',
            null,
            'pending'
        );
    }
}
```

## Database Queries

### Get Recent Activities
```php
$activities = ActivityLog::orderBy('performed_at', 'desc')
    ->limit(10)
    ->get();
```

### Get Activities for Specific Patient
```php
$activities = ActivityLog::where('patient_name', 'John Smith')
    ->orderBy('performed_at', 'desc')
    ->get();
```

### Get Activities by Type
```php
$prescriptions = ActivityLog::where('action_type', 'like', 'prescription_%')
    ->orderBy('performed_at', 'desc')
    ->get();
```

### Get Activities by Status
```php
$pending = ActivityLog::where('status', 'pending')
    ->orderBy('performed_at', 'desc')
    ->get();
```

### Get Today's Activities
```php
$today = ActivityLog::whereDate('performed_at', today())
    ->orderBy('performed_at', 'desc')
    ->get();
```

## Model Attributes

### Computed Attributes
```php
$log = ActivityLog::first();

// Get status badge color class
$color = $log->status_color;  // Returns: 'success', 'warning', 'danger', 'info'

// Get relative time
$time = $log->time_since;      // Returns: "5 minutes ago", "2 hours ago"
```

### Direct Properties
```php
$log->action_type          // "prescription_sent"
$log->description          // "Prescription for Amoxicillin sent to CVS"
$log->patient_name         // "Sarah Martinez"
$log->patient_initials     // "SM"
$log->reference_number     // "RX #9425"
$log->details              // "Amoxicillin 500mg - 3x daily for 10 days"
$log->performed_by         // "Dr. House"
$log->status               // "approved"
$log->performed_at         // Carbon instance
```

## View Usage

### In Blade Templates
```blade
@if($activityLogs && $activityLogs->count() > 0)
    @foreach($activityLogs as $log)
        <div>
            {{ $log->description }}
            <span class="badge bg-{{ $log->status_color }}">
                {{ $log->status }}
            </span>
        </div>
    @endforeach
@else
    <p>No activities found</p>
@endif
```

## Best Practices

### ✅ DO:
- Use descriptive action descriptions
- Include patient name and reference numbers
- Log important clinical actions
- Use appropriate status badges
- Keep details concise but informative

### ❌ DON'T:
- Log technical/system events
- Include sensitive data (passwords, tokens)
- Log every page view
- Use vague descriptions
- Duplicate logs for the same action

## Testing

### Test Activity Logging
```php
public function test_prescription_approval_creates_activity_log()
{
    // Approve prescription
    $response = $this->post('/patients/1/process', [
        'action' => 'approve',
        'medication' => 'Amoxicillin 500mg'
    ]);
    
    // Assert log was created
    $this->assertDatabaseHas('activity_logs', [
        'action_type' => 'prescription_sent',
        'patient_name' => 'John Smith',
        'status' => 'approved'
    ]);
}
```

## Troubleshooting

### Issue: Activities not showing on dashboard
**Solution**: Check that controller is passing `$activityLogs` to view:
```php
return view('dashboard', compact('activityLogs'));
```

### Issue: Patient initials not displaying
**Solution**: Ensure `patient_name` is set when creating log. Initials auto-extract from name.

### Issue: Status badge color not working
**Solution**: Use predefined statuses: `approved`, `pending`, `completed`, `cancelled`

### Issue: Timestamps showing wrong time
**Solution**: Check timezone in `config/app.php`:
```php
'timezone' => 'UTC',
```

## Performance Tips

1. **Limit query results**: Use `->limit(10)` for dashboard
2. **Index columns**: `performed_at` is already indexed
3. **Eager load relationships**: Add relationships if needed
4. **Cache dashboard data**: For high-traffic apps
5. **Background logging**: Use queues for heavy logging

## Summary

The Activity Logs feature is easy to use:

1. Add `LogsActivity` trait to controller
2. Call logging methods when actions occur
3. Activities automatically appear on dashboard
4. No additional configuration needed

For questions or issues, refer to `ACTIVITY_LOGS_FEATURE.md` for detailed documentation.
