# Enhanced Photo System Implementation Guide
**KSO Chandigarh Management System**

## Overview

The Enhanced Photo System provides advanced photo upload capabilities with chunked uploads, real-time progress tracking, optimized image processing, and real-time member status indicators. This system supports large file uploads, multiple image formats, automatic optimization, and seamless user experience.

## Features Implemented

### 📸 Photo Upload System
- **Chunked Upload Support**: Handles large files (up to 50MB) by breaking them into manageable chunks
- **Drag & Drop Interface**: Modern, intuitive file selection with visual feedback
- **Real-time Progress**: Live progress bars with upload speed and time remaining
- **Multiple Format Support**: JPEG, PNG, GIF, WebP with automatic conversion
- **Image Optimization**: Automatic thumbnail and optimized version generation
- **WebP Support**: Modern format support for better compression
- **Client-side Preview**: Instant preview generation before upload
- **Upload Validation**: Comprehensive file validation and security checks

### 👥 Real-time Status System
- **Online Status Tracking**: Live member online/offline indicators
- **Activity Monitoring**: Real-time activity tracking and logging
- **Status Categories**: Online, Recently Active, Away, Offline with visual indicators
- **Member Activity Feed**: Live feed of member activities
- **Heartbeat System**: Automatic status updates via periodic pings
- **Session Management**: Secure session tracking and management

### 🖼️ Image Processing & Optimization
- **Multi-size Generation**: Original, optimized, and thumbnail versions
- **WebP Conversion**: Automatic WebP format generation for modern browsers
- **Lazy Loading**: Progressive image loading for better performance
- **Responsive Images**: Adaptive image serving based on device capabilities
- **Secure Storage**: Protected file storage with access controls

## File Structure

```
📁 Database Schema
├── database/enhanced_photo_system.sql          # Complete database setup

📁 Backend APIs
├── api/photos/enhanced.php                     # Photo upload API endpoints
├── api/status/realtime.php                     # Real-time status API
├── api/services/EnhancedPhotoService.php       # Photo processing service

📁 Frontend Components
├── frontend/js/enhanced-photo-system.js        # JavaScript functionality
├── frontend/assets/css/enhanced-photo-system.css # Styling
├── frontend/pages/enhanced-photos.html         # Demo page

📁 Storage Directories
├── uploads/member-photos/
│   ├── originals/                              # Original uploaded files
│   ├── optimized/                              # Optimized versions
│   ├── thumbnails/                             # Thumbnail versions
│   └── temp/                                   # Temporary upload files
```

## Database Schema

### Core Tables

#### `member_photos`
- Stores photo metadata and processing status
- Links photos to members
- Tracks upload information and file variations

#### `member_online_status`
- Real-time member online status
- Session tracking and activity monitoring
- Login/logout timestamps

#### `photo_upload_sessions`
- Tracks chunked upload sessions
- Progress monitoring and session management
- Cleanup and expiration handling

#### `member_activity_log`
- Comprehensive activity logging
- Security and audit trail
- Performance analytics

### Key Features
- **Foreign Key Constraints**: Data integrity and referential consistency
- **Indexes**: Optimized for real-time queries and performance
- **Triggers**: Automatic status updates and maintenance
- **Views**: Simplified data access for common queries
- **Procedures**: Automated cleanup and maintenance tasks

## API Endpoints

### Photo Upload APIs (`/api/photos/enhanced.php`)

#### POST Endpoints
- `?path=upload-chunk` - Upload file chunk
- `?path=upload-complete` - Complete chunked upload
- `?path=upload-traditional` - Traditional single-file upload
- `?path=set-profile-photo` - Set member profile photo

#### GET Endpoints
- `?path=member-photos` - Get member photos
- `?path=photo-info` - Get specific photo information
- `?path=upload-status` - Check upload progress
- `?path=activity-status` - Get member activity status
- `?path=online-members` - Get online members list

#### PUT Endpoints
- `?path=update-activity` - Update member activity

#### DELETE Endpoints
- `?path=photo` - Delete photo
- `?path=cancel-upload` - Cancel ongoing upload

### Real-time Status APIs (`/api/status/realtime.php`)

#### GET Endpoints
- `?path=online-status` - Get member online status
- `?path=member-activity` - Get member activity history
- `?path=activity-feed` - Get activity feed
- `?path=heartbeat` - Ping for status update

#### POST Endpoints
- `?path=track-activity` - Track member activity
- `?path=login-activity` - Track login events
- `?path=logout-activity` - Track logout events

#### PUT Endpoints
- `?path=heartbeat` - Update member heartbeat
- `?path=status` - Update member status

## Frontend Components

### EnhancedPhotoUpload Class

```javascript
const photoUpload = new EnhancedPhotoUpload({
    dropZone: '#photo-drop-zone',
    fileInput: '#photo-file-input',
    chunkSize: 5 * 1024 * 1024, // 5MB chunks
    maxFileSize: 50 * 1024 * 1024, // 50MB max
    onUploadComplete: (session) => {
        console.log('Upload completed:', session.result);
    }
});
```

### MemberStatusTracker Class

```javascript
const statusTracker = new MemberStatusTracker({
    memberId: 1,
    updateInterval: 30000, // 30 seconds
    onStatusUpdate: (members) => {
        updateOnlineMembersList(members);
    }
});
statusTracker.start();
```

### LazyImageLoader Class

```javascript
const lazyLoader = new LazyImageLoader({
    selector: '.lazy-image',
    rootMargin: '50px'
});
```

## Security Implementation

### API Security
- **CSRF Protection**: Token-based request validation
- **Session Validation**: Secure session management
- **Rate Limiting**: Prevents abuse and DoS attacks
- **Input Sanitization**: All inputs properly sanitized
- **File Validation**: Comprehensive file type and content validation

### File Security
- **Secure Storage**: Files stored outside web root when possible
- **Access Controls**: .htaccess protection for sensitive directories
- **File Validation**: MIME type and content validation
- **Hash Verification**: Chunk integrity verification
- **Secure Filenames**: Generated secure filenames

### Privacy Protection
- **Data Encryption**: Sensitive data encrypted in transit
- **Access Logging**: Comprehensive audit trails
- **Permission Checks**: Role-based access controls
- **Session Security**: Secure session management

## Performance Optimizations

### Upload Performance
- **Chunked Uploads**: Handles large files efficiently
- **Parallel Processing**: Concurrent chunk uploads
- **Progress Tracking**: Real-time progress indicators
- **Resume Capability**: Upload resumption on connection issues

### Image Performance
- **Multiple Formats**: WebP for modern browsers, fallbacks for older ones
- **Lazy Loading**: Progressive image loading
- **Responsive Images**: Appropriate sizes for different devices
- **CDN Ready**: Structure supports CDN integration

### Database Performance
- **Optimized Indexes**: Fast queries for real-time features
- **Efficient Queries**: Minimal database hits
- **Connection Pooling**: Efficient database connections
- **Cleanup Procedures**: Automated maintenance

## Setup Instructions

### 1. Database Setup

```sql
-- Run the database setup script
SOURCE database/enhanced_photo_system.sql;

-- Set up cleanup cron jobs
-- Add to crontab:
-- */5 * * * * mysql -u username -p database_name -e "CALL cleanup_offline_members();"
-- 0 * * * * mysql -u username -p database_name -e "CALL cleanup_expired_upload_sessions();"
```

### 2. Directory Setup

```bash
# Create upload directories
mkdir -p uploads/member-photos/{originals,optimized,thumbnails,temp}

# Set proper permissions
chmod 755 uploads/member-photos/
chmod 755 uploads/member-photos/{originals,optimized,thumbnails,temp}

# Create security files
touch uploads/member-photos/.htaccess
echo "deny from all" > uploads/member-photos/.htaccess
```

### 3. PHP Configuration

```ini
; Recommended PHP settings for large file uploads
upload_max_filesize = 50M
post_max_size = 50M
max_execution_time = 300
memory_limit = 256M
max_input_time = 300
```

### 4. Frontend Integration

```html
<!-- Include CSS -->
<link rel="stylesheet" href="frontend/assets/css/enhanced-photo-system.css">

<!-- Include JavaScript -->
<script src="frontend/js/enhanced-photo-system.js"></script>

<!-- Add CSRF token -->
<meta name="csrf-token" content="<?php echo $_SESSION['csrf_token']; ?>">

<!-- Add member ID for status tracking -->
<body data-member-id="<?php echo $member_id; ?>">
```

## Usage Examples

### Basic Photo Upload

```html
<!-- Drop zone HTML -->
<div id="photo-drop-zone" class="photo-drop-zone">
    <i class="fas fa-cloud-upload-alt drop-icon"></i>
    <div class="drop-text">Drag & drop photos here</div>
</div>

<!-- Progress container -->
<div id="upload-progress" class="upload-progress-container"></div>

<!-- Preview container -->
<div id="photo-preview" class="photo-preview-container"></div>
```

```javascript
// Initialize upload system
const photoUpload = new EnhancedPhotoUpload({
    memberId: 1,
    onUploadComplete: function(session) {
        showNotification('Photo uploaded successfully!', 'success');
        refreshGallery();
    },
    onUploadError: function(error) {
        showNotification(`Upload failed: ${error.message}`, 'error');
    }
});
```

### Real-time Status Display

```html
<!-- Online members widget -->
<div class="online-members-widget">
    <div class="online-members-header">
        <h5>Online Members</h5>
        <span class="online-members-count">0</span>
    </div>
    <div id="online-members-list" class="online-members-list">
        <!-- Members will be populated here -->
    </div>
</div>
```

```javascript
// Initialize status tracker
const statusTracker = new MemberStatusTracker({
    memberId: currentMemberId,
    onStatusUpdate: function(members) {
        updateOnlineMembersList(members);
    },
    onOnlineCountUpdate: function(count) {
        document.querySelector('.online-members-count').textContent = count;
    }
});

statusTracker.start();
```

### Lazy Loading Images

```html
<!-- Lazy loaded images -->
<img class="lazy-image" 
     data-src="/uploads/member-photos/optimized/photo.jpg"
     data-webp="/uploads/member-photos/optimized/photo.webp"
     alt="Member Photo">
```

## API Usage Examples

### Upload File via API

```javascript
// Chunked upload
const uploadFile = async (file) => {
    const fileId = generateFileId();
    const chunkSize = 5 * 1024 * 1024; // 5MB
    const chunks = Math.ceil(file.size / chunkSize);
    
    for (let i = 0; i < chunks; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, file.size);
        const chunk = file.slice(start, end);
        
        await fetch('/api/photos/enhanced.php?path=upload-chunk', {
            method: 'POST',
            headers: {
                'X-Chunk-Index': i.toString(),
                'X-Total-Chunks': chunks.toString(),
                'X-File-Id': fileId,
                'X-Original-Name': file.name,
                'X-CSRF-Token': getCSRFToken()
            },
            body: chunk
        });
    }
    
    // Complete upload
    const result = await fetch('/api/photos/enhanced.php?path=upload-complete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': getCSRFToken()
        },
        body: JSON.stringify({
            file_id: fileId,
            member_id: memberId
        })
    });
    
    return await result.json();
};
```

### Track Member Activity

```javascript
// Track activity
const trackActivity = async (memberId, activityType, details) => {
    const response = await fetch('/api/status/realtime.php?path=track-activity', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': getCSRFToken()
        },
        body: JSON.stringify({
            member_id: memberId,
            activity_type: activityType,
            details: details
        })
    });
    
    return await response.json();
};
```

### Get Online Members

```javascript
// Get online members
const getOnlineMembers = async () => {
    const response = await fetch('/api/status/realtime.php?path=online-status&limit=50');
    const data = await response.json();
    
    if (data.success) {
        return {
            members: data.members,
            counts: data.counts
        };
    }
    
    throw new Error(data.error || 'Failed to fetch online members');
};
```

## Troubleshooting

### Common Issues

#### Upload Failures
- **Large File Issues**: Check PHP upload limits and server timeout settings
- **Chunk Assembly**: Verify temp directory permissions and disk space
- **Progress Tracking**: Ensure upload session tracking is working

#### Status Tracking Issues
- **Offline Detection**: Check cleanup procedures and timeout settings
- **Real-time Updates**: Verify API endpoints and polling intervals
- **Session Management**: Ensure proper session handling

#### Performance Issues
- **Slow Uploads**: Check network, server resources, and chunk size
- **Database Performance**: Verify indexes and query optimization
- **Image Processing**: Check GD/ImageMagick configuration

### Debug Mode

Enable debug mode by adding to your config:

```php
// Debug mode for enhanced photo system
define('PHOTO_DEBUG', true);

// Additional logging
ini_set('log_errors', 1);
ini_set('error_log', 'logs/photo_system.log');
```

### Monitoring

Check these files for monitoring:
- `logs/photo_system.log` - Photo system specific logs
- `logs/api_access.log` - API access logs
- Database activity logs in `member_activity_log` table

## Maintenance

### Regular Tasks

1. **Database Cleanup**
   - Run cleanup procedures daily
   - Archive old activity logs
   - Clean up expired upload sessions

2. **File Cleanup**
   - Remove orphaned files
   - Clean temp directories
   - Optimize storage usage

3. **Performance Monitoring**
   - Monitor upload success rates
   - Check API response times
   - Review error logs

### Backup Considerations

- Backup upload directories regularly
- Include database schema and data
- Test restoration procedures
- Monitor storage usage

## Security Checklist

- [ ] CSRF protection enabled
- [ ] File validation implemented
- [ ] Rate limiting configured
- [ ] Access controls in place
- [ ] Secure file storage
- [ ] Session management secure
- [ ] Error handling proper
- [ ] Logging comprehensive
- [ ] Input sanitization complete
- [ ] Permission checks implemented

## Future Enhancements

### Planned Features
- **Bulk Upload**: Multiple file selection and batch processing
- **Image Editing**: Basic editing capabilities (crop, rotate, filters)
- **Cloud Storage**: Integration with cloud storage providers
- **Advanced Compression**: AI-powered image optimization
- **WebSocket Support**: True real-time updates without polling

### Integration Opportunities
- **CDN Integration**: Content delivery network support
- **Mobile App**: React Native or Flutter integration
- **Social Features**: Photo sharing and commenting
- **Analytics**: Advanced upload and usage analytics

---

This enhanced photo system provides a robust, scalable foundation for photo management with real-time features. The modular design allows for easy extension and customization based on specific requirements.
