# Product Mail Controller Documentation

**File**: `/controllers/productmail.php`  
**Purpose**: Email product lists and inventory information with HTML formatting  
**Last Updated**: December 20, 2024  
**Total Functions**: 1+  
**Lines of Code**: ~171

---

## 📋 Overview

Simple controller for emailing formatted product information. Features:
- HTML email formatting
- Product table generation
- Supplier information integration
- Category-based filtering interface
- Custom message composition

### Primary Functions
- [x] HTML email composition
- [x] Product table formatting
- [x] Supplier integration
- [x] Category filtering interface

---

## 🗄️ Database Tables

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **supplier** | Supplier information | supplierid, suppliername |
| **productcat** | Product categories | productCatId, productCatName |
| **programsettings** | System settings | programsettingsid, reportsPlusHours |

---

## 🔑 Key Functions

### 1. **Email Generation** - HTML Email Creation
**Location**: Line 116  
**Purpose**: Generate and send formatted product emails

**HTML Email Structure**:
```php
$txt .= '<html><meta http-equiv="content-type" content="text/html; charset=UTF-8" />
         <body><div style="border-color:#777;border-style:solid;border-width:1px;
         border-radius:30px;padding:20px;">';

$txt .= '<p align="center;" style="font-size:20px;">
         <div style="text-align:right">
         <strong style="color: blue;">' . $msg . '</strong></div></p><br/>';

$txt .= '<table style="width:100%;direction: rtl"><thead>';
$txt .= '<tr style="background-color:#757575;color:white;">
         <th style="text-align:right">المنتج</th>
         <th style="text-align:right">الكمية</th></tr></thead><tbody>';

for ($i = 0; $i < $itr; $i++) {
    $productName = filter_input(INPUT_POST, "productName" . $i);
    $quantity = filter_input(INPUT_POST, "quantity" . $i);
    
    if (isset($productName) && !empty($productName) && isset($quantity) && !empty($quantity)) {
        $txt .= ($i % 2 == 0) ? '<tr>' : '<tr style="background-color:#ddd;">';
        $txt .= '<td style="text-align:right">' . $productName . '</td>
                 <td style="text-align:right">' . $quantity . '</td></tr>';
    }
}
```

**Email Sending**:
```php
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= "From: info@test.net\r\n" . "X-Mailer: php";

mail($to, $subject, $txt, $headers);
```

---

## 🔄 Workflows

### Workflow: Email Generation
```
┌─────────────────────────────────────────┐
│      START: Compose Email              │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  1. Form Preparation                    │
│     - Load categories                   │
│     - Load suppliers                    │
│     - Display composition form          │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  2. Content Processing                  │
│     - Extract email address            │
│     - Process custom message           │
│     - Parse product list               │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  3. HTML Generation                     │
│     - Create HTML structure            │
│     - Format product table             │
│     - Apply alternating row colors     │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  4. Email Dispatch                      │
│     - Set HTML headers                  │
│     - Send formatted email             │
│     - Redirect to success page         │
└─────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default | Email composition form |
| `do=send` | Email processing | Send formatted email |

### Required Parameters
**Send Email** (`do=send`):
- `mail` - Recipient email address
- `title` - Email subject line
- `editor1` - Custom message content
- `itr` - Number of products
- `productName{N}` - Product names (dynamic)
- `quantity{N}` - Product quantities (dynamic)

---

## 🧮 Calculation Methods

### Dynamic Product Processing
```php
$itr = filter_input(INPUT_POST, "itr");  // Number of products

for ($i = 0; $i < $itr; $i++) {
    $productName = filter_input(INPUT_POST, "productName" . $i);
    $quantity = filter_input(INPUT_POST, "quantity" . $i);
    
    // Only include if both name and quantity exist
    if (isset($productName) && !empty($productName) && 
        isset($quantity) && !empty($quantity)) {
        // Add to email table
    }
}
```

### Alternating Row Styling
```php
if ($i % 2 == 0) {
    $txt .= '<tr>';
} else {
    $txt .= '<tr style="background-color:#ddd;">';
}
```

---

## 🔒 Security & Permissions

### Authentication
```php
include_once("../public/authentication.php");
```

### Input Sanitization
```php
$mail = filter_input(INPUT_POST, "mail");
$title = filter_input(INPUT_POST, "title");
$msg = filter_input(INPUT_POST, "editor1");
$itr = filter_input(INPUT_POST, "itr");
```

### Email Security
- HTML content escaping needed
- Email validation recommended
- Rate limiting should be considered

---

## ⚠️ Issues Identified

### 1. **Security Vulnerabilities**
- No email validation
- No HTML escaping for product names
- No rate limiting for email sending

### 2. **Missing Features**
- No email delivery confirmation
- No attachment support
- No email templates

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Email
```
1. Enter valid email address
2. Add product list with quantities
3. Verify HTML formatting
4. Check email delivery
```

### Test Case 2: Edge Cases
```
1. Test with empty product list
2. Test with special characters in product names
3. Test invalid email addresses
4. Verify error handling
```

---

## 📚 Recommendations

### Security Improvements
```php
// Add email validation
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
    throw new Exception("Invalid email address");
}

// Escape HTML content
$productName = htmlspecialchars($productName, ENT_QUOTES, 'UTF-8');
```

---

**Documented By**: AI Assistant  
**Review Status**: ⚠️ Needs Review - Security vulnerabilities identified  
**Next Review**: Add input validation and security improvements