# SmartThink3 LMS Platform

A comprehensive, globally-structured Learning Management System (LMS) with advanced geo-location controls, WhatsApp integration, and AI-powered learning enhancements.

## 🌍 Overview

SmartThink3 LMS is a modern, intelligent digital learning platform designed to deliver professional training, certifications, and skills development across three major regions: USA, Europe, and Africa. The platform integrates a robust backend Content Management System (CMS), advanced geo-location controls, WhatsApp real-time communication, and AI-powered learning features.

## 🚀 Key Features

### 🌐 Global & Regional Access
- **Geo-Location Detection**: Automatic IP-based location detection
- **Regional Access Control**: Content and pricing based on user's region
- **Compliance Management**: GDPR (Europe), US data protection, African regulations
- **Multi-Currency Support**: USD, EUR, NGN with automatic conversion
- **Regional Content**: Tailored courses and resources per region

### 📚 Learning Management System
- **Course Management**: Modular courses with videos, PDFs, labs, and live sessions
- **Progress Tracking**: Real-time learning progress and analytics
- **Assessments & Quizzes**: Automated and manual grading with certificates
- **Interactive Content**: Rich media support and downloadable resources
- **Learning Paths**: AI-powered course recommendations

### 💬 WhatsApp Integration
- **Real-Time Support**: 24/7 WhatsApp chat with AI and human agents
- **Automated Notifications**: Course updates, payment confirmations, completion alerts
- **Interactive Bots**: Smart chatbots for FAQs and course guidance
- **Human Takeover**: Seamless escalation to human support when needed

### 🏢 Custom CMS
- **User Management**: Role-based access control (Admin, Instructor, Student)
- **Content Management**: Dynamic content creation and management
- **Analytics Dashboard**: Comprehensive reporting and insights
- **System Configuration**: Flexible settings and customization options

### 🎯 Gamification & Engagement
- **Achievement System**: Badges, points, levels, and milestones
- **Learning Streaks**: Daily engagement tracking
- **Leaderboards**: Regional and global rankings
- **Certificates**: QR-code verified professional certificates

### 💳 E-Commerce & Payments
- **Multiple Gateways**: Stripe, PayPal, Mobile Money (Africa)
- **Regional Pricing**: Automatic currency conversion and regional pricing
- **Secure Transactions**: PCI-compliant payment processing
- **Subscription Management**: Recurring billing and course packages

## 📋 System Requirements

### Server Requirements
- **PHP**: 8.0 or higher
- **MySQL**: 5.7 or higher / MariaDB 10.2+
- **Web Server**: Apache 2.4+ or Nginx 1.18+
- **SSL Certificate**: Required for production
- **Memory**: Minimum 512MB RAM (1GB+ recommended)

### PHP Extensions
- PDO & PDO_mysql
- cURL
- JSON
- GD
- OpenSSL
- Mbstring
- Zip
- XML

### Optional Dependencies
- Redis (for caching)
- Elasticsearch (for advanced search)
- FFmpeg (for video processing)

### Database Migrations
A simple migration runner is included at `scripts/run_migrations.php`. Run it after pulling changes to apply new tables:

```bash
php scripts/run_migrations.php
```

### FFmpeg (thumbnails)
If you want automatic video thumbnail extraction, install `ffmpeg` and set `FFMPEG_PATH` in `config/media.php` (default `/usr/bin/ffmpeg`). The app will try to generate a poster image for uploaded videos if available.

## 🛠️ Installation Guide

### 1. Database Setup
```sql
-- Import the database schema
mysql -u username -p database_name < database/schema.sql
```

### 2. Configuration
```bash
# Copy configuration template
cp config/database.example.php config/database.php

# Edit configuration
nano config/database.php
```

### 3. File Permissions
```bash
# Set proper permissions
chmod 755 uploads/
chmod 755 logs/
chmod 755 cache/
```

### 4. Web Server Configuration

#### Apache (.htaccess)
```apache
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
```

#### Nginx
```nginx
location / {
    try_files $uri $uri/ /index.php?$query_string;
}
```

### 5. Environment Setup
```php
// config/database.php
define('APP_ENV', 'production'); // or 'development'
define('APP_URL', 'https://your-domain.com');
define('DB_HOST', 'localhost');
define('DB_NAME', 'smartthink3_lms');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');
```

## 📁 Project Structure

```
smartthink/
├── public/                 # Public website files
├── website/               # Frontend website
│   ├── index.html        # Main homepage
│   └── assets/           # CSS, JS, images
├── lms/                   # Learning Management System
│   ├── dashboard.php     # Student dashboard
│   ├── courses.php       # Course listing
│   ├── course.php        # Individual course
│   └── includes/         # LMS components
├── cms/                   # Admin Panel
│   ├── dashboard.php     # Admin dashboard
│   ├── users.php         # User management
│   ├── courses.php       # Course management
│   └── includes/         # CMS components
├── api/                   # API endpoints
│   └── v1/               # API version 1
├── classes/               # PHP classes
│   ├── User.php          # User management
│   ├── Course.php        # Course management
│   ├── GeoLocation.php   # Geo-location services
│   └── WhatsApp.php      # WhatsApp integration
├── config/                # Configuration files
│   └── database.php      # Database configuration
├── database/              # Database files
│   └── schema.sql        # Database schema
├── uploads/               # User uploads
├── logs/                  # System logs
└── assets/                # Shared assets
    ├── css/              # Stylesheets
    ├── js/               # JavaScript files
    └── images/           # Images and media
```

## 🔧 Configuration

### Database Configuration
Edit `config/database.php`:
```php
define('DB_HOST', 'localhost');
define('DB_NAME', 'smartthink3_lms');
define('DB_USER', 'your_username');
define('DB_PASS', 'your_password');
```

### WhatsApp Integration
```php
define('WHATSAPP_PHONE_ID', 'your-phone-id');
define('WHATSAPP_ACCESS_TOKEN', 'your-access-token');
define('WHATSAPP_WEBHOOK_URL', APP_URL . '/api/whatsapp/webhook');
```

### Payment Gateways
```php
// Stripe
define('STRIPE_PUBLISHABLE_KEY', 'pk_test_...');
define('STRIPE_SECRET_KEY', 'sk_test_...');

// PayPal
define('PAYPAL_CLIENT_ID', 'your-paypal-client-id');
define('PAYPAL_CLIENT_SECRET', 'your-paypal-secret');
```

### Geo-Location Services
```php
define('GEO_API_KEY', 'your-geo-api-key');
define('FEATURE_GEOLOCATION', true);
define('ENFORCE_REGION_ACCESS', true);
```

## 🌐 Regional Configuration

### Supported Regions
- **USA**: USD currency, US compliance, English language
- **Europe**: EUR currency, GDPR compliance, multiple languages
- **Africa**: NGN currency, African regulations, local payment methods

### Regional Settings
```php
// Regional pricing multipliers
'regional_multipliers' => [
    'usa' => 1.0,
    'europe' => 0.85,
    'africa' => 0.0024
],

// Regional compliance
'compliance' => [
    'usa' => [
        'data_retention_days' => 365,
        'cookie_consent_required' => true,
        'tax_rate' => 0.08
    ],
    'europe' => [
        'data_retention_days' => 730,
        'cookie_consent_required' => true,
        'tax_rate' => 0.21,
        'gdpr_compliant' => true
    ],
    'africa' => [
        'data_retention_days' => 180,
        'cookie_consent_required' => false,
        'tax_rate' => 0.05
    ]
]
```

## 📱 WhatsApp Integration

### Setup Steps
1. Create a Meta Business Account
2. Set up WhatsApp Business API
3. Configure webhooks
4. Create message templates
5. Test integration

### Message Templates
```php
// Welcome message
$whatsapp->sendTemplateMessage($phone, 'welcome_message', 'en_US', [
    [
        'type' => 'body',
        'parameters' => [
            ['type' => 'text', 'text' => $userName]
        ]
    ]
]);

// Course enrollment notification
$whatsapp->sendEnrollmentNotification($userId, $courseId);

// Payment confirmation
$whatsapp->sendPaymentConfirmation($userId, $amount, $currency);
```

## 🔒 Security Features

### Authentication & Authorization
- **Secure Password Hashing**: Argon2ID algorithm
- **Session Management**: Secure session handling with expiration
- **Role-Based Access**: Granular permissions by user role
- **Two-Factor Authentication**: Optional 2FA support

### Data Protection
- **Encryption**: AES-256 encryption for sensitive data
- **Input Validation**: Comprehensive input sanitization
- **SQL Injection Prevention**: Prepared statements
- **XSS Protection**: Output encoding and CSP headers

### Compliance
- **GDPR Compliant**: Full GDPR implementation for Europe
- **Data Retention**: Configurable data retention policies
- **Cookie Management**: GDPR-compliant cookie consent
- **Privacy by Design**: Privacy-focused architecture

## 📊 Analytics & Reporting

### User Analytics
- **Registration Trends**: New user signups by region
- **Learning Patterns**: Course completion rates
- **Engagement Metrics**: Time spent, lesson completion
- **Geographic Distribution**: User locations and demographics

### Business Analytics
- **Revenue Reports**: Income by region and course
- **Conversion Rates**: Enrollment conversion tracking
- **Course Performance**: Popular courses and ratings
- **Support Metrics**: WhatsApp response times

### Technical Analytics
- **System Performance**: Server load and response times
- **Error Tracking**: Comprehensive error logging
- **API Usage**: API call statistics and monitoring
- **Security Events**: Failed logins and access violations

## 🚀 Deployment

### Production Deployment
```bash
# 1. Set up production environment
export APP_ENV=production

# 2. Optimize for production
php -d opcache.enable=1 -d opcache.memory_consumption=256

# 3. Set up SSL certificate
certbot --nginx -d yourdomain.com

# 4. Configure backup
crontab -e
# Add: 0 2 * * * /path/to/backup-script.sh

# 5. Set up monitoring
# Configure monitoring tools (New Relic, DataDog, etc.)
```

### Docker Deployment
```dockerfile
FROM php:8.1-fpm-alpine

# Install dependencies
RUN apk add --no-cache \
    nginx \
    mysql-client \
    curl

# Copy application files
COPY . /var/www/html

# Set permissions
RUN chown -R www-data:www-data /var/www/html

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```

## 🧪 Testing

### Unit Tests
```bash
# Run PHPUnit tests
./vendor/bin/phpunit tests/

# Generate coverage report
./vendor/bin/phpunit --coverage-html coverage/
```

### Integration Tests
```bash
# Run API tests
./vendor/bin/phpunit tests/api/

# Run WhatsApp integration tests
./vendor/bin/phpunit tests/whatsapp/
```

### Load Testing
```bash
# Use Apache Bench
ab -n 1000 -c 10 https://your-domain.com/

# Use JMeter for complex scenarios
jmeter -n test-plan.jmx -l results.jtl
```

## 📈 Performance Optimization

### Database Optimization
- **Indexing**: Proper database indexes for fast queries
- **Query Optimization**: Efficient SQL queries
- **Connection Pooling**: Database connection management
- **Caching**: Redis for frequently accessed data

### Frontend Optimization
- **Minification**: CSS and JavaScript minification
- **Image Optimization**: WebP format and lazy loading
- **CDN Integration**: Content delivery network for static assets
- **Browser Caching**: Proper cache headers

### Server Optimization
- **PHP OPcache**: Bytecode caching
- **Gzip Compression**: Response compression
- **Load Balancing**: Multiple server instances
- **CDN**: Global content delivery

## 🔄 API Documentation

### Authentication
```http
POST /api/v1/auth/login
Content-Type: application/json

{
    "username": "user@example.com",
    "password": "password123"
}
```

### Course Management
```http
GET /api/v1/courses
Authorization: Bearer {token}

POST /api/v1/courses
Authorization: Bearer {token}
Content-Type: application/json

{
    "title": "Course Title",
    "description": "Course Description",
    "category_id": 1,
    "price": 99.99
}
```

### WhatsApp Webhook
```http
POST /api/whatsapp/webhook
Content-Type: application/json

{
    "object": "whatsapp_business_account",
    "entry": [{
        "changes": [{
            "value": {
                "messages": [{
                    "from": "1234567890",
                    "id": "msg_id",
                    "text": {"body": "Hello"},
                    "timestamp": "1234567890",
                    "type": "text"
                }]
            }
        }]
    }]
}
```

## 🛠️ Maintenance

### Regular Tasks
- **Database Backups**: Daily automated backups
- **Log Rotation**: Weekly log cleanup
- **Security Updates**: Monthly security patches
- **Performance Monitoring**: Continuous performance tracking

### Troubleshooting
```bash
# Check error logs
tail -f logs/error.log

# Check database connections
mysql -u username -p -e "SHOW PROCESSLIST;"

# Check server status
systemctl status nginx php-fpm mysql

# Monitor disk space
df -h
```

## 🤝 Contributing

### Development Workflow
1. Fork the repository
2. Create feature branch
3. Make changes and test
4. Submit pull request
5. Code review and merge

### Coding Standards
- **PSR-12**: Follow PHP coding standards
- **Documentation**: Comprehensive code comments
- **Testing**: Write tests for new features
- **Security**: Follow security best practices

## 📞 Support

### Documentation
- **User Guide**: Comprehensive user documentation
- **Admin Manual**: Administrator guide
- **API Reference**: Complete API documentation
- **FAQ**: Frequently asked questions

### Contact
- **Email**: support@smartthink3.com
- **WhatsApp**: +1 (555) 123-4567
- **Support Portal**: https://support.smartthink3.com
- **Community Forum**: https://community.smartthink3.com

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🎯 Roadmap

### Version 1.1 (Q2 2026)
- [ ] Mobile apps (iOS/Android)
- [ ] Advanced AI recommendations
- [ ] Virtual classroom integration
- [ ] Multi-language support expansion

### Version 1.2 (Q3 2026)
- [ ] Corporate training portals
- [ ] Advanced analytics dashboard
- [ ] Integration with popular tools
- [ ] Enhanced gamification features

### Version 2.0 (Q4 2026)
- [ ] Microlearning modules
- [ ] AI-powered content creation
- [ ] Blockchain certificates
- [ ] Global marketplace

---

**SmartThink3 LMS** - Empowering Global Learning Through Innovation 🚀📚
