# Advertisement Controller Documentation

**File**: `/controllers/ads.php`  
**Purpose**: Manages advertisement content with multi-language support and image handling  
**Last Updated**: December 20, 2024  
**Total Functions**: 5  
**Lines of Code**: 204

---

## 📋 Overview

The Advertisement Controller is a content management system specifically designed for handling promotional content and advertisements. It provides:
- Advertisement creation and management
- Multi-language content support (Arabic/English)
- Image upload and management
- Location-based ad placement
- Active/inactive status control
- CRUD operations with soft delete
- File management with cleanup
- Tutorial integration

### Primary Functions
- [x] Advertisement creation and editing
- [x] Multi-language content management
- [x] Image upload and processing
- [x] Location-based ad categorization
- [x] Active/inactive status management
- [x] Soft delete with file cleanup
- [x] Content listing and display
- [x] Tutorial resource integration

### Related Controllers
- [firms.php](firms.md) - Company management
- [propertiesController.php](propertiesController.md) - Property management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **ads** | Advertisement content | id, title, titleEn, content, contentEn, image, location, isActive, sysDate, userid, isdel |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |

### File Storage Structure
| Directory | Purpose | File Types |
|-----------|---------|------------|
| `/upload/ads/` | Advertisement images | JPG, PNG, GIF |

---

## 🔑 Key Functions

### 1. **Default Action / Advertisement Form** - Ad Management Interface
**Location**: Line 54  
**Purpose**: Display advertisement creation/management interface

**Function Signature**:
```php
// Triggered when: $do is empty (default action)
$smarty->display("adsview/add.html");
```

**Features**:
- Clean form interface for ad creation
- Multi-language input fields
- Image upload capability
- Location and status selection

---

### 2. **add()** - Create New Advertisement
**Location**: Line 57  
**Purpose**: Create new advertisement with image upload and multi-language support

**Function Signature**:
```php
elseif ($do == "add")
// Called via: POST request with advertisement data and optional image
```

**Process Flow**:
1. Extract and validate POST data
2. Handle image upload using `uploadnew()` function
3. Create new ad record using RedBeanPHP
4. Set system metadata (date, user, status)
5. Return JSON response for AJAX or redirect for standard form

**Data Processing**:
```php
$title = $_POST['title'];           // Arabic title
$titleEn = $_POST['titleEn'];       // English title
$content = $_POST['content'];       // Arabic content
$contentEn = $_POST['contentEn'];   // English content
$location = $_POST['location'];     // Ad placement location
$isActive = (int) $_POST['isActive']; // Active status (0/1)
$image = uploadnew('image', False, 0, 0, 'ads'); // Image upload
```

**Record Creation**:
```php
$rdispense = R::dispense('ads');
$rdispense->title = $title;
$rdispense->titleEn = $titleEn;
$rdispense->image = $image;
$rdispense->content = $content;
$rdispense->contentEn = $contentEn;
$rdispense->location = $location;
$rdispense->isActive = $isActive;
$rdispense->sysDate = date("Y-m-d H:i:s");
$rdispense->userid = $_SESSION['userid'];
$rdispense->isdel = 0;
$id = R::store($rdispense);
```

---

### 3. **show()** - Advertisement Listing
**Location**: Line 75  
**Purpose**: Display all active advertisements with management options

**Function Signature**:
```php
elseif ($do == "show")
// Displays: All non-deleted advertisements
```

**Process Flow**:
1. Query all non-deleted advertisements
2. Load tutorial resources
3. Display via `adsview/show.html` template
4. Enable custom validation features

**Query Logic**:
```php
$showData = R::findAll('ads', 'isdel = 0');
$youtubes = $youtubeLinkDAO->queryAll();
$smarty->assign('showData', $showData);
$smarty->assign("youtubes", $youtubes);
$smarty->assign("customCheck", 1);
```

---

### 4. **edit() / update()** - Advertisement Modification
**Location**: Line 103 (edit), Line 109 (update)  
**Purpose**: Edit existing advertisement content

**Edit Process Flow**:
```php
$id = $_GET['id'];
$showData = R::load('ads', $id);
$smarty->assign('showData', $showData);
$smarty->display("adsview/edit.html");
```

**Update Process Flow**:
1. Load existing advertisement record
2. Update all content fields
3. Handle image update using `uploadupdate()` function
4. Preserve existing image if no new upload
5. Save changes and respond appropriately

**Image Update Logic**:
```php
$image = uploadupdate('image', 'imageurl', False, 0, 0, 'ads');
$rupdate = R::load('ads', $id);
// ... update other fields ...
$rupdate->image = $image;
$id = R::store($rupdate);
```

---

### 5. **deleteFinaly()** - Permanent Advertisement Deletion
**Location**: Line 84 (action), Line 198 (function)  
**Purpose**: Permanently delete advertisement with file cleanup

**Function Signature**:
```php
function deleteFinaly($id)
// Called when: permanent deletion requested
```

**Process Flow**:
1. Load advertisement record
2. Check for associated image file
3. Remove file from filesystem with proper permissions
4. Permanently delete database record
5. Handle response for AJAX or standard requests

**File Cleanup Logic**:
```php
function deleteFinaly($id) {
    $rtrash = R::load('ads', $id);
    if (file_exists('../upload/ads/' . $rtrash->image)) {
        chmod('../upload/ads/' . $rtrash->image, 0777);
        unlink('../upload/ads/' . $rtrash->image);
    }
    R::trash($rtrash);
}
```

---

## 🔄 Workflows

### Workflow 1: Advertisement Creation
```
┌─────────────────────────────────────────────────────────────┐
│                START: Create Advertisement                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Content Definition                                      │
│     Multi-language input:                                   │
│       │                                                     │
│       ├─→ Arabic title and content                         │
│       ├─→ English title and content                        │
│       ├─→ Location/placement category                      │
│       ├─→ Active status (0/1)                              │
│       └─→ Image file upload (optional)                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Image Processing                                        │
│     IF image uploaded:                                      │
│       │                                                     │
│       ├─→ Validate file type and size                      │
│       ├─→ Generate unique filename                         │
│       ├─→ Save to /upload/ads/ directory                   │
│       └─→ Return filename for database storage             │
│     ELSE:                                                   │
│       │                                                     │
│       └─→ Set empty image field                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Database Record Creation                                │
│     INSERT INTO ads:                                        │
│       │                                                     │
│       ├─→ title, titleEn                                   │
│       ├─→ content, contentEn                               │
│       ├─→ image filename                                   │
│       ├─→ location, isActive                               │
│       ├─→ sysDate (current timestamp)                      │
│       ├─→ userid (session user)                            │
│       └─→ isdel = 0 (not deleted)                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Response Handling                                       │
│     IF AJAX request (curlpost = 1):                        │
│       │                                                     │
│       └─→ Return JSON success/error response               │
│     ELSE standard form:                                     │
│       │                                                     │
│       └─→ Redirect to success/error page                   │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Advertisement Editing
```
┌─────────────────────────────────────────────────────────────┐
│              START: Edit Advertisement                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Existing Data                                      │
│     - Query advertisement by ID                             │
│     - Populate form fields with current values             │
│     - Display existing image (if any)                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Update Processing                                       │
│     Update content fields:                                  │
│       │                                                     │
│       ├─→ Arabic and English titles/content                │
│       ├─→ Location and status changes                      │
│       └─→ Handle image update/replacement                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Image Update Logic                                      │
│     IF new image uploaded:                                  │
│       │                                                     │
│       ├─→ Process new image upload                         │
│       ├─→ Delete old image file (if exists)                │
│       └─→ Update image field with new filename             │
│     ELSE keep existing:                                     │
│       │                                                     │
│       └─→ Preserve current image value                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Changes                                            │
│     - Update database record                                │
│     - Handle success/error responses                        │
│     - Redirect or return JSON result                        │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Advertisement creation form |
| `do=add` | `add()` | Create new advertisement |
| `do=show` | `show()` | List all advertisements |
| `do=edit` | `edit()` | Edit advertisement form |
| `do=update` | `update()` | Update advertisement |
| `do=deleteFinaly` | `deleteFinaly()` | Permanent deletion |
| `do=sucess` | Success page | Operation completed |
| `do=error` | Error page | Operation failed |

### Required Parameters by Action

**Add Advertisement** (`do=add`):
- `title` - Arabic title
- `titleEn` - English title
- `content` - Arabic content
- `contentEn` - English content
- `location` - Placement location
- `isActive` - Status (0 or 1)
- `image` - Image file (optional)

**Edit Advertisement** (`do=edit`):
- `id` - Advertisement ID

**Update Advertisement** (`do=update`):
- `id` - Advertisement ID
- All fields from add operation
- `imageurl` - Current image (for reference)

**Delete Advertisement** (`do=deleteFinaly`):
- `id` - Advertisement ID to delete

---

## 🔒 Security & Permissions

### Input Sanitization
```php
// Direct POST access (consider adding validation)
$title = $_POST['title'];
$isActive = (int) $_POST['isActive']; // Type casting for integer
```

### File Upload Security
- Images uploaded to restricted `/upload/ads/` directory
- File type validation handled by upload functions
- File permissions set properly during deletion

### Access Control
- User ID stored with each advertisement
- Session-based user tracking
- Consider adding role-based permissions for ad management

### AJAX Security
```php
// AJAX request detection
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    // Handle AJAX-specific logic
    // Return JSON responses
}
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `ads(isdel, isActive)` for listing queries
   - `ads(userid)` for user-based filtering
   - `ads(location)` for location-based queries

2. **Query Optimization**:
   - Use soft delete pattern (`isdel = 0`)
   - Filter active ads efficiently
   - Consider pagination for large ad collections

3. **File Management**:
   - Regular cleanup of orphaned image files
   - Image optimization for web delivery
   - Consider CDN for image serving

### Memory Management
- Image upload size limits
- Content length restrictions
- Efficient template variable assignment

---

## 🐛 Common Issues & Troubleshooting

### 1. **Image Upload Failures**
**Issue**: Images not uploading or displaying  
**Cause**: Permission issues or upload directory problems

**Debug**:
```php
// Check upload directory permissions
if (!is_writable('../upload/ads/')) {
    echo "Upload directory not writable";
}

// Verify uploaded file
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    echo "Upload error: " . $_FILES['image']['error'];
}
```

### 2. **File Deletion Issues**
**Issue**: Old images not deleted during updates  
**Cause**: File permission or path problems

**Debug**:
```php
// Check file existence and permissions
$filePath = '../upload/ads/' . $oldImage;
if (file_exists($filePath)) {
    if (!is_writable($filePath)) {
        chmod($filePath, 0777);
    }
    unlink($filePath);
}
```

### 3. **Multi-language Content Issues**
**Issue**: Character encoding problems with Arabic content  
**Cause**: Database charset or template encoding

**Solution**:
```sql
-- Ensure proper charset
ALTER TABLE ads CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

### 4. **AJAX Response Issues**
**Issue**: Inconsistent responses between AJAX and standard forms  
**Cause**: Mixed response handling logic

**Standardize**:
```php
// Consistent response format
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    echo json_encode(['status' => 1, 'message' => 'Success']);
} else {
    header("location:?do=sucess");
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Advertisement Creation
```
1. Access advertisement creation form
2. Fill out multi-language content
3. Upload test image
4. Submit and verify success
5. Check image file saved correctly
6. Verify database record created
```

### Test Case 2: Image Management
```
1. Create ad with image
2. Edit ad and replace image
3. Verify old image deleted
4. Test deletion without image
5. Check file cleanup on permanent delete
```

### Test Case 3: Multi-language Support
```
1. Create ad with Arabic and English content
2. Verify both languages stored correctly
3. Test special characters and Unicode
4. Check template display in both languages
```

### Test Case 4: AJAX vs Standard Forms
```
1. Test creation via AJAX (curlpost=1)
2. Test creation via standard form
3. Verify consistent behavior
4. Check response format differences
```

### Test Case 5: Status and Location Filtering
```
1. Create ads with different statuses
2. Create ads in different locations
3. Test filtering by active/inactive
4. Verify location-based categorization
```

---

## 🚀 Future Enhancement Opportunities

### 1. **Advanced Content Management**
- Rich text editor integration
- Content versioning and history
- Content approval workflows
- Scheduled publication dates

### 2. **Enhanced Image Handling**
- Multiple image support per ad
- Image resizing and optimization
- Gallery view for image management
- Image alt text and metadata

### 3. **Location and Targeting**
- Geographic targeting options
- Demographic targeting
- A/B testing capabilities
- Performance analytics

### 4. **SEO and Analytics**
- Meta tag management
- Click tracking and analytics
- SEO optimization features
- Performance reporting dashboard

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [File Upload Guidelines](#) - Image handling best practices
- [Multi-language Content Guide](#) - Internationalization standards

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When content management features are enhanced