# Copilot Instructions for Mutalex LMS Codebase

## Architecture Overview

**Mutalex Academy LMS** is a multi-role Learning Management System built on PHP/MySQL with integrated payment processing and AI capabilities.

### Core Components:
- **Auth System** (`config/auth.php`, `config/rbac.php`): Session-based authentication with role-based access control (Admin, Instructor, Student, Guest)
- **Payment Gateway** (`includes/payments.php`): Dual gateway support (Paynow SDK, PayPal SDK via Composer)
- **Database Layer** (`config/database.php`): PDO-based MySQL connection with `yujbjplf_lms` database
- **AI/ML Features** (`api/ai/`): OpenAI integration for content analysis, question generation, translation, essay evaluation
- **Calendar System**: Firebase Firestore integration for real-time event management

### URL Structure:
- Root → `home.php` (landing)
- Admin → `/admin/dashboard.php`
- Instructor → `/instructor/` (course creation, grading)
- Student → `/student/dashboard.php` (enrollment, progress)
- API endpoints → `/api/` (RESTful, JSON responses)

## Critical Files & Patterns

### 1. Authentication & Session Management
**Files:** `config/auth.php`, `includes/functions.php`

- Sessions persist for 30 minutes (`SESSION_LIFETIME` in `config/security.php`)
- Session regeneration every 10 minutes for security
- Always call `requireLogin()` or `requireAnyRole()` at top of protected pages
- User session stored in `$_SESSION['user_id']`, `$_SESSION['role']`, `$_SESSION['username']`

**Pattern:**
```php
<?php
require_once '../includes/functions.php';
requireAnyRole(['admin', 'instructor']); // Protect page
```

### 2. Database Operations
**Pattern:** Always use PDO prepared statements to prevent SQL injection
```php
$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ? AND instructor_id = ?");
$stmt->execute([$course_id, $_SESSION['user_id']]);
$course = $stmt->fetch(); // Returns associative array
```

### 3. Payment Processing Pipeline
**Files:** `includes/payments.php` (Main gateway), `Paynow-PHP-SDK-master/` (SDK), PayPal SDK via Composer

**Flow:**
1. Create transaction record with `createTransaction()` → stores status='pending'
2. Redirect user to payment gateway URL
3. Gateway processes payment, calls webhook endpoint
4. Webhook updates transaction status and triggers post-payment actions (enrollment, certificate, email notification)

**Key Methods:** `initializePayment()`, `verifyPayment()`, `validateDiscountCode()`

**Payment Currencies:** Configured in `config/currency.php` and `admin/currency_settings.php`

### 4. Role-Based Access Control (RBAC)
**File:** `config/rbac.php`

Permissions mapped to roles in `PERMISSIONS` array:
- `view_courses` → guest, student, instructor, admin
- `create_course` → instructor, admin
- `manage_users` → admin only

**Usage Pattern:**
```php
if (hasPermission('edit_own_course')) {
    // Display edit form
}
requirePermission('delete_course'); // Redirects if unauthorized
```

### 5. Email Notifications
**File:** `includes/notifications.php`

- Handles registration confirmation, password reset, enrollment confirmations, payment receipts
- Email template system for consistent branding
- Trigger on events: user registration, payment completion, course enrollment

## Development Conventions

### Code Style:
- **Functions** use snake_case: `registerUser()`, `getDB()`
- **Variables** use snake_case: `$user_id`, `$course_name`
- **Constants** use UPPER_CASE: `MAX_FILE_SIZE`, `SESSION_LIFETIME`
- **Classes** use PascalCase: `PaymentGateway`, `AIAnalytics`

### File Upload Security
**File:** `config/security.php`
- Max size: 5MB (`MAX_FILE_SIZE`)
- Allowed types: jpg, jpeg, png, gif, pdf, doc, docx
- Always use `handleFileUpload()` function which:
  - Validates file type and size
  - Generates secure random filename with `bin2hex(random_bytes(16))`
  - Stores in `/uploads/` directory

### Error Handling:
- Use `try-catch` for database operations, file handling, external API calls
- Log errors via `error_log()` for debugging
- Return structured responses: `['success' => bool, 'message' => string, 'data' => mixed]`

### Environment Variables:
- Stored in `.env` file (auto-loaded via vendor/phpdotenv)
- Used for: API keys, database credentials, email settings
- Never commit `.env` to version control

## API Standards

### Endpoint Conventions:
- **Resources:** Plural nouns (`/api/courses/`, `/api/users/`)
- **Actions:** Use HTTP verbs (GET read, POST create, PUT update, DELETE remove)
- **Response Format:** JSON with status codes
  ```json
  {
    "success": true,
    "data": { /* resource data */ },
    "message": "Success message"
  }
  ```

### Examples:
- `GET /api/courses` → List all courses
- `POST /api/courses` → Create course (instructor only)
- `GET /api/enrollments?course_id=5` → Get enrollments for course
- `POST /api/payments` → Create payment transaction

## AI Integration Workflow

**Files:** `api/ai/`, `config/ai.php`

### Supported Features:
- **Content Analysis:** Analyze course content for readability, accessibility
- **Question Generation:** Auto-generate quiz questions from lesson text
- **Essay Evaluation:** Grade essay assignments with feedback
- **Learning Path:** Recommend courses based on user performance
- **Translation:** Multi-language content support
- **Performance Analysis:** Student progress insights

**Pattern:**
```php
require_once 'config/ai.php';
$analyzer = new AIContentAnalyzer();
$result = $analyzer->analyze($courseContent);
// Returns: readability_score, accessibility_issues, suggestions
```

## Important Workflow Notes

### Adding New Endpoints:
1. Create file in `/api/` folder
2. Implement authentication check: `requireLogin()`
3. Verify permission: `hasPermission('required_permission')`
4. Use PDO prepared statements for DB queries
5. Return JSON response with success/error

### Database Migrations:
- Migration files in root directory: `create_*_migration.php`, `add_*_migration.php`
- Run migrations manually or via dashboard
- Follow naming: `create_[table_name]_migration.php`

### Testing:
- Test files: `test_auth.php`, `test_questions.php`, `test_sample_exams.php`
- Manual database testing in `/admin/payment_test.php`

## Key External Dependencies

- **PayPal SDK** (`vendor/paypal/paypal-server-sdk`): Orders, payments, vault management
- **Paynow SDK** (`Paynow-PHP-SDK-master`): Local payment processing
- **OpenAI PHP Client** (`openai-php/client`): AI content features
- **phpdotenv** (`vlucas/phpdotenv`): Environment variable management

## Security Checklist

Before deploying:
- [ ] Verify `.env` contains all required keys and is not in git
- [ ] Database credentials use proper user with limited permissions
- [ ] File uploads validate extension and size
- [ ] All user inputs sanitized with `sanitizeInput()`
- [ ] Sessions timeout after 30 minutes
- [ ] CSRF tokens validated on state-changing forms
- [ ] Rate limiting enabled for login attempts (5 attempts = 15min lockout)
- [ ] Payment transactions logged and auditable
