# Boarding Controller Documentation

**File**: `/controllers/boarding.php`  
**Purpose**: Application onboarding content management for mobile apps and tutorials  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: ~206

---

## 📋 Overview

The Boarding Controller manages onboarding and tutorial content for mobile applications and system help. It handles:
- Creating and managing onboarding slides/screens
- Multi-language content support (Arabic/English)
- Image upload and management for onboarding screens
- Position-based ordering of content slides
- Active/inactive status management
- Integration with mobile apps via cURL/API support
- Tutorial video linking through YouTube integration

### Primary Functions
- [x] Create new onboarding content with images
- [x] Edit and update existing onboarding slides
- [x] Multi-language content (title, content in AR/EN)
- [x] Image upload with automatic file management
- [x] Position-based slide ordering
- [x] Active/inactive status toggle
- [x] Complete content deletion with file cleanup
- [x] API-compatible responses for mobile integration

### Related Controllers
- [api.php](api.md) - Mobile API integration
- [programsettingsController.php](programsettingsController.md) - System configuration
- [youtubeLinkController.php](#) - Tutorial video management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **boarding** | Onboarding content storage | id, title, titleEn, content, contentEn, image, position, isActive, sysDate, userid, isdel |

### Reference Tables (Used)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **user** | Content creators | userid, username |

### File Storage
| Location | Purpose | File Types |
|----------|---------|------------|
| `/upload/boarding/` | Onboarding images | JPG, PNG, GIF |

---

## 🔑 Key Functions

### 1. **Default Action / Add Form** - Empty `do`
**Location**: Line 54  
**Purpose**: Display form for creating new onboarding content

**Process Flow**:
1. Check user authentication (implicit)
2. Display `boardingview/add.html` template
3. Form includes fields for both Arabic and English content

**Template Variables**: None (form only)

---

### 2. **add()** - Create New Onboarding Content
**Location**: Line 57 (route), Line 151 (function)  
**Purpose**: Process new onboarding slide creation with image upload

**Form Parameters**:
```php
$title = $_POST['title'];           // Arabic title
$titleEn = $_POST['titleEn'];       // English title
$content = $_POST['content'];       // Arabic content/description
$contentEn = $_POST['contentEn'];   // English content/description
$position = (int) $_POST['position']; // Display order
$isActive = (int) $_POST['isActive']; // 1=active, 0=inactive
// Image uploaded via 'image' file field
```

**Process Flow**:
1. Extract form data and cast types appropriately
2. Upload image using `uploadnew()` function:
   - Destination: `boarding` directory
   - No resize applied (False parameters)
   - Auto-generates filename
3. Create new RedBean object for `boarding` table
4. Set all fields including system timestamps
5. Store record and return ID

**Image Upload**:
```php
$image = uploadnew('image', False, 0, 0, 'boarding');
// Returns filename for storage in database
```

**Response Handling**:
- **Regular Form**: Redirect to `?do=sucess`
- **API/cURL**: Return JSON response with status and message

---

### 3. **show()** - List All Onboarding Content
**Location**: Line 75  
**Purpose**: Display all onboarding content for management

**Process Flow**:
1. Query all non-deleted boarding records: `R::findAll('boarding', 'isdel = 0')`
2. Load YouTube tutorial links for help
3. Assign data to Smarty template
4. Display `boardingview/show.html`
5. Set custom validation flag

**Template Variables**:
- `$showData` - Array of boarding content records
- `$youtubes` - Tutorial video links
- `$customCheck = 1` - Enable custom validation

---

### 4. **edit()** - Display Edit Form
**Location**: Line 103  
**Purpose**: Load existing content for modification

**Process Flow**:
1. Get ID from URL parameter: `$id = $_GET['id']`
2. Load specific record: `R::load('boarding', $id)`
3. Assign record to template
4. Display `boardingview/edit.html`

**Features**: Pre-populates form with existing values for modification

---

### 5. **update()** - Update Existing Content
**Location**: Line 109 (route), Line 175 (function)  
**Purpose**: Modify existing onboarding content with optional image replacement

**Process Flow**:
1. Get record ID from POST data
2. Load existing record from database
3. Update all text fields with new values
4. Handle image upload with `uploadupdate()`:
   - Only uploads new image if file provided
   - Uses 'imageurl' as fallback field name
   - Automatically removes old image files
5. Save updated record

**Image Update Logic**:
```php
$image = uploadupdate('image', 'imageurl', False, 0, 0, 'boarding');
// Handles both new uploads and keeping existing images
```

---

### 6. **deleteFinaly()** - Complete Content Removal
**Location**: Line 84 (route), Line 198 (function)  
**Purpose**: Permanently delete onboarding content with file cleanup

**Process Flow**:
1. Get ID from URL parameter: `$id = (int) $_GET['id']`
2. Load record to access image filename
3. Delete physical image file from server:
   ```php
   if (file_exists('../upload/boarding/' . $rtrash->image)) {
       chmod('../upload/boarding/' . $rtrash->image, 0777);
       unlink('../upload/boarding/' . $rtrash->image);
   }
   ```
4. Permanently delete database record: `R::trash($rtrash)`

**File Management**: Ensures no orphaned files remain after deletion

---

## 🔄 Workflows

### Workflow 1: Creating Onboarding Content
```
┌─────────────────────────────────────────────────────────────┐
│            START: New Onboarding Content Creation          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Content Planning                                        │
│     - Prepare Arabic and English text                      │
│     - Design onboarding image/graphic                       │
│     - Determine slide position in sequence                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Form Submission                                         │
│     - Enter title (Arabic + English)                       │
│     - Enter content/description (Arabic + English)         │
│     - Upload image file                                     │
│     - Set position number                                   │
│     - Set active status                                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Processing                                              │
│     - Validate form inputs                                  │
│     - Upload image to /upload/boarding/                     │
│     - Generate unique filename                              │
│     - Insert record to database                             │
│     - Set system fields (userid, sysDate)                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Mobile App Integration                                  │
│     - Content available via API                             │
│     - Images accessible via URL path                        │
│     - Position-based ordering maintained                    │
│     - Language switching supported                          │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Content Management and Updates
```
┌─────────────────────────────────────────────────────────────┐
│              START: Content Modification                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Content Review                                          │
│     - View existing onboarding slides                       │
│     - Identify content needing updates                      │
│     - Check image quality and relevance                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Edit Process                                            │
│     - Load edit form with current data                      │
│     - Modify text content as needed                         │
│     - Replace image if required                             │
│     - Adjust position or active status                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Processing                                       │
│     - Save text changes to database                         │
│     - Handle image replacement:                             │
│       ├─ Delete old image file                             │
│       ├─ Upload new image                                  │
│       └─ Update database reference                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Content Removal (if needed)                            │
│     - Delete content permanently                            │
│     - Remove associated image files                         │
│     - Clean up database records                             │
│     - Update mobile app content                             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function | Description |
|---------------|----------|-------------|
| `do=` (empty) | Display form | Show onboarding content creation form |
| `do=add` | `add()` | Process new content creation |
| `do=show` | List content | Display all onboarding slides for management |
| `do=edit&id=X` | Load edit form | Display existing content for editing |
| `do=update` | `update()` | Process content modifications |
| `do=deleteFinaly&id=X` | `deleteFinaly()` | Permanently delete content and files |
| `do=sucess` | Success page | Display operation success message |
| `do=error` | Error page | Display operation error message |

### cURL/API Support
All actions support both web form submissions and API calls:
```php
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    // Return JSON response for API calls
    $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
    echo json_encode($data);
} else {
    // Standard web redirect
    header("location:?do=sucess");
}
```

---

## 🧮 Data Management

### Database Schema
```sql
CREATE TABLE boarding (
    id INT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255),              -- Arabic title
    titleEn VARCHAR(255),            -- English title  
    content TEXT,                    -- Arabic content
    contentEn TEXT,                  -- English content
    image VARCHAR(255),              -- Image filename
    position INT,                    -- Display order
    isActive TINYINT(1),            -- 1=active, 0=inactive
    sysDate DATETIME,               -- Creation timestamp
    userid INT,                     -- Creator user ID
    isdel TINYINT(1) DEFAULT 0      -- Soft delete flag
);
```

### Image File Management
```php
// Upload new image
$image = uploadnew('image', False, 0, 0, 'boarding');

// Update existing (keeps old if no new file)
$image = uploadupdate('image', 'imageurl', False, 0, 0, 'boarding');

// File paths
$imagePath = '../upload/boarding/' . $filename;
$webPath = '/upload/boarding/' . $filename;
```

### Content Ordering
```php
// Position-based ordering for mobile apps
ORDER BY position ASC, id ASC

// Active content filtering  
WHERE isdel = 0 AND isActive = 1
```

---

## 🔒 Security & Permissions

### Access Control
```php
// Session validation on sensitive actions (implicit through include)
include_once("../public/authentication.php");
```

### File Upload Security
- Images stored in designated upload directory
- File type validation through upload functions
- Automatic filename generation prevents conflicts
- Directory permissions managed (chmod 0777 for deletion)

### Input Validation
```php
$id = (int) $_GET['id'];              // Cast to integer
$position = (int) $_POST['position']; // Validate position
$isActive = (int) $_POST['isActive']; // Boolean validation
```

### Soft Delete Protection
- Records marked `isdel = 1` instead of physical deletion
- `deleteFinaly` provides permanent removal option
- File cleanup only on permanent deletion

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Required**:
   - `boarding(isdel, isActive, position)`
   - `boarding(userid, sysDate)` for admin queries

2. **Query Patterns**:
   - Frequent active content queries: `isdel = 0 AND isActive = 1`
   - Position-based ordering: `ORDER BY position ASC`
   - Single record loads by ID

3. **File Storage**:
   - Images stored locally, not in database
   - Consider CDN for mobile app performance
   - Regular cleanup of orphaned image files

### Mobile API Performance
```php
// Mobile-optimized queries
SELECT id, title, titleEn, content, contentEn, image, position 
FROM boarding 
WHERE isdel = 0 AND isActive = 1 
ORDER BY position ASC;

// Minimize data transfer for mobile
SELECT id, title, titleEn, image, position 
FROM boarding 
WHERE isdel = 0 AND isActive = 1;
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Image Upload Failures**
**Issue**: Images not uploading or displaying  
**Cause**: Directory permissions or upload function errors

**Fix**:
```bash
# Check upload directory exists and is writable
ls -la ../upload/
chmod 755 ../upload/boarding/

# Verify upload functions are available
grep -r "function uploadnew" ../library/
```

### 2. **Content Not Appearing in Mobile App**
**Issue**: New content doesn't show in mobile application  
**Cause**: `isActive = 0` or API caching issues

**Debug**:
```sql
-- Check content status
SELECT id, title, isActive, isdel, position FROM boarding ORDER BY position;

-- Verify active content count
SELECT COUNT(*) FROM boarding WHERE isdel = 0 AND isActive = 1;
```

### 3. **File Deletion Errors**
**Issue**: `deleteFinaly` fails to remove image files  
**Cause**: File permissions or missing files

**Fix**:
```php
// Debug file deletion
if (file_exists('../upload/boarding/' . $filename)) {
    echo "File exists: " . $filename;
    chmod('../upload/boarding/' . $filename, 0777);
    if (unlink('../upload/boarding/' . $filename)) {
        echo "File deleted successfully";
    } else {
        echo "Failed to delete file";
    }
}
```

### 4. **Position Ordering Issues**
**Issue**: Content appears in wrong order in mobile app  
**Cause**: Duplicate positions or missing position values

**Fix**:
```sql
-- Check for position conflicts
SELECT position, COUNT(*) as count FROM boarding 
WHERE isdel = 0 GROUP BY position HAVING count > 1;

-- Reset positions sequentially
SET @row_number = 0;
UPDATE boarding SET position = (@row_number:=@row_number + 1) 
WHERE isdel = 0 ORDER BY position, id;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Complete Content Lifecycle
```
1. Create new onboarding content with image
2. Verify image uploaded to correct directory
3. Check content appears in show listing
4. Edit content and replace image
5. Confirm old image file removed
6. Test soft delete (isdel = 1)
7. Test permanent deletion with file cleanup
```

### Test Case 2: Multi-language Support
```
1. Create content with both Arabic and English text
2. Verify both language versions stored correctly
3. Test API responses include both languages
4. Check character encoding for Arabic text
5. Validate mobile app language switching
```

### Test Case 3: Mobile API Integration
```
1. Submit content via cURL with curlpost=1
2. Verify JSON response format
3. Test error handling with invalid data
4. Check image URL accessibility
5. Validate position-based ordering
```

### Test Case 4: File Management
```
1. Upload various image formats (JPG, PNG, GIF)
2. Test large file uploads
3. Verify filename uniqueness
4. Test file deletion on content removal
5. Check orphaned file cleanup
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [api.md](api.md) - Mobile API integration
- [File Upload Documentation](#) - Upload function specifications
- [Mobile App Documentation](#) - Integration guidelines

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When mobile app onboarding features change or image management updates needed