# Global Notification System Documentation

## Overview
The StyleScore 2025 notification system provides real-time notifications across all pages of the application. It supports categorized notifications with filtering capabilities and role-based access control.

## Files Structure

### Core Files
- `/includes/notifications.php` - Main notification system included on every page via db.php
- `/api/notification_api.php` - Backend API for notification management
- `/assets/js/notification_manager.js` - Frontend JavaScript manager
- `/includes/db.php` - Database connection file (includes notifications.php)

### Test Files
- `/admin/test_notifications.php` - Comprehensive test page for all notification features

## Features

### Notification Categories
- **general** - General announcements and information
- **competition** - Competition-related events and updates
- **participant** - Participant-specific notifications (on start, completed, etc.)
- **judge** - Judge actions and scoring notifications
- **system** - System status and technical messages
- **heat** - Heat activation, deactivation, and management
- **scoring** - Score updates and calculations
- **technical** - Technical issues and system diagnostics

### Notification Types
- **success** (green) - Successful operations and completions
- **danger** (red) - Errors, emergency stops, critical issues
- **warning** (yellow) - Warnings and cautions
- **info** (blue) - Information and status updates

### Role-Based Filtering
- **Admin** - Sees all notification categories
- **Judge** - Sees judge, scoring, participant, and heat notifications
- **Staff** - Sees competition, participant, heat, and general notifications
- **Viewer** - Sees general and competition notifications only

## Usage

### Automatic Integration
The notification system is automatically available on every page that includes `db.php`. No additional setup is required.

### Quick Functions
```javascript
// Basic notifications
notifySuccess('Title', 'Message');
notifyError('Title', 'Message');
notifyWarning('Title', 'Message');
notifyInfo('Title', 'Message');

// Advanced notification with category
sendNotification('success', 'Title', 'Message', 'category');
```

### Competition-Specific Functions
```javascript
// Participant notifications
notifyParticipant('on_start', bibNumber, participantName);
notifyParticipant('started', bibNumber, participantName);
notifyParticipant('completed', bibNumber, participantName);
notifyParticipant('next', bibNumber, participantName);

// Heat notifications
notifyHeat('activated', heatNumber, runNumber);
notifyHeat('deactivated', heatNumber);

// Judge notifications
notifyJudge('Score Submitted', 'Details about the action');

// Scoring notifications
notifyScore(participantBib, score, judgeName);

// Emergency notifications
notifyEmergencyStop();
```

### Category Filtering
```javascript
// Set specific categories to show
globalNotificationManager.setCategoryFilters(['participant', 'heat']);

// Add a category to current filters
globalNotificationManager.addCategoryFilter('judge');

// Remove a category from filters
globalNotificationManager.removeCategoryFilter('system');

// Clear all filters (show all notifications)
globalNotificationManager.clearCategoryFilters();
```

## UI Components

### Notification Controls
- **Filter Buttons** - Category-based filtering
- **Status Indicator** - Connection status (LIVE/LOCAL/DISCONNECTED)
- **Notification Counter** - Shows total notifications received
- **Clear All Button** - Clears all notifications for the current event

### Toast Notifications
- **Auto-hide Timers** - Different durations based on importance
- **Category Badges** - Visual category identification
- **Sound Alerts** - Audio feedback for critical notifications
- **Manual Dismiss** - Click to close notifications

## Configuration

### Event Detection
The system automatically detects the current event ID from:
1. Session variable `$_SESSION['current_event_id']`
2. URL parameter `$_GET['event_id']`
3. Form data `$_POST['event_id']`
4. Most recent event from database (fallback)

### User Detection
User identification is determined from:
1. `$_SESSION['user_id']`
2. `$_SESSION['username']`
3. `$_SESSION['user']`
4. Falls back to 'anonymous'

### Role Detection
User roles are detected from:
1. `$_SESSION['user_type']`
2. `$_SESSION['role']`
3. `$_SESSION['admin_logged_in']`
4. `$_SESSION['judge_logged_in']`
5. Falls back to 'viewer'

## Database Schema

### event_notifications Table
```sql
CREATE TABLE event_notifications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_id INT NOT NULL,
    type ENUM('success', 'danger', 'warning', 'info') DEFAULT 'info',
    category ENUM('general', 'competition', 'participant', 'judge', 'system', 'heat', 'scoring', 'technical') DEFAULT 'general',
    title VARCHAR(255) NOT NULL,
    message TEXT,
    user_id VARCHAR(100) DEFAULT 'system',
    data JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_event_created (event_id, created_at),
    INDEX idx_event_id (event_id),
    INDEX idx_category (category),
    INDEX idx_event_category (event_id, category)
);
```

### notification_reads Table
```sql
CREATE TABLE notification_reads (
    id INT AUTO_INCREMENT PRIMARY KEY,
    notification_id INT NOT NULL,
    user_id VARCHAR(100) NOT NULL,
    read_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_read (notification_id, user_id),
    FOREIGN KEY (notification_id) REFERENCES event_notifications(id) ON DELETE CASCADE
);
```

## API Endpoints

### Send Notification
```
POST /api/notification_api.php
Parameters:
- action: 'send_notification'
- event_id: Event ID
- type: Notification type (success/danger/warning/info)
- category: Notification category
- title: Notification title
- message: Notification message (optional)
- user_id: Sender ID
- data: Additional JSON data (optional)
```

### Get Notifications
```
GET /api/notification_api.php
Parameters:
- action: 'get_notifications'
- event_id: Event ID
- since: Last notification ID received (for polling)
- limit: Maximum notifications to return
- category: Filter by category (optional)
```

### Mark as Read
```
POST /api/notification_api.php
Parameters:
- action: 'mark_read'
- notification_id: Notification ID
- user_id: User ID
```

### Clear All Notifications
```
POST /api/notification_api.php
Parameters:
- action: 'clear_all'
- event_id: Event ID
```

## Error Handling

### Connection Issues
- **Local Mode** - Falls back to local-only notifications when API is unavailable
- **Automatic Retry** - Exponential backoff for reconnection attempts
- **Status Indicators** - Visual feedback for connection state

### Database Issues
- **Graceful Degradation** - System works without database connection
- **Fallback Configuration** - Uses default database settings if config missing
- **Error Logging** - Non-intrusive error handling

## Testing

### Test Page
Visit `/admin/test_notifications.php` to test all notification features:
- Basic notification types
- Category-specific notifications
- Competition functions
- Quick utility functions
- System integration status

### Manual Testing
1. Open any page in the application
2. Look for the bell icon in the top-right corner
3. Click to access notification controls
4. Test different categories and filters
5. Monitor the status indicator for connection state

## Best Practices

### For Developers
1. Always specify appropriate categories for notifications
2. Use descriptive titles and helpful messages
3. Include relevant data in the notification payload
4. Test with different user roles
5. Handle API failures gracefully

### For Users
1. Set category filters based on your role
2. Pay attention to color coding for urgency
3. Use the clear function to manage notification clutter
4. Monitor the connection status indicator
5. Report any connectivity issues

## Troubleshooting

### Common Issues
1. **Notifications not appearing** - Check event ID and user session
2. **Connection errors** - Verify API path and database configuration
3. **Wrong categories** - Check role-based filtering settings
4. **Missing sounds** - Browser audio permissions may be required
5. **Layout issues** - Check for CSS conflicts with existing styles

### Debug Information
- Browser console shows detailed connection and error information
- Network tab displays API request/response details
- Status indicator provides real-time connection feedback
- Test page validates all system components
