# Ex Controller Documentation

**File**: `/controllers/ex.php`  
**Purpose**: Experimental controller and program settings management  
**Last Updated**: December 20, 2024  
**Total Functions**: 2  
**Lines of Code**: ~201

---

## 📋 Overview

The Ex Controller serves as an experimental/utility controller primarily focused on program settings management. It handles:
- System configuration updates
- Company profile management
- Logo and branding updates
- System preferences
- Image upload processing
- Configuration validation

### Primary Functions
- [x] Display system settings form
- [x] Update program configuration
- [x] Logo upload and management
- [x] Company information updates
- [x] Print settings configuration
- [x] System preference management

### Related Controllers
- [programsettingsController.php](programsettingsController.md) - Main settings controller
- [login.php](login.md) - System initialization
- [index.php](index.md) - Dashboard

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **programsettings** | System configuration | programsettingsid, companyname, address, phone, email, logo |

### Configuration Fields
| Field Name | Purpose | Data Type |
|------------|---------|----------|
| **companyname** | Company name | VARCHAR |
| **address** | Company address | TEXT |
| **specializtion** | Business specialization | VARCHAR |
| **phone** | Contact phone | VARCHAR |
| **faxnumber** | Fax number | VARCHAR |
| **email** | Contact email | VARCHAR |
| **website** | Company website | VARCHAR |
| **logo** | Company logo path | VARCHAR |
| **roundnumbers** | Number rounding setting | INT |
| **saveprinting** | Save print setting | INT |
| **deptprinting** | Department printing | INT |
| **printingpapersize** | Paper size setting | VARCHAR |
| **previousPrice** | Show previous prices | INT |
| **parcode** | Barcode settings | INT |
| **priceing** | Pricing method | INT |
| **lastprice** | Last price display | INT |
| **searchvalue** | Search configuration | INT |
| **updateproductprice** | Price update setting | INT |

---

## 🔑 Key Functions

### 1. **Default Action** - Settings Display
**Location**: Line 54  
**Purpose**: Display program settings form for editing

**Process Flow**:
1. Load current program settings (ID = 1)
2. Assign settings data to template
3. Display settings form (add.html)

**Template Variables**:
```php
$programsettingsdata = $ProgramsettingDAO->load(1);
$smarty->assign('programsettingsdata', $programsettingsdata);
```

**Features**:
- Load existing configuration
- Form pre-population
- Setting validation
- User-friendly interface

---

### 2. **update()** - Settings Update Function
**Location**: Line 120  
**Purpose**: Process and save program settings updates

**Function Signature**:
```php
function update() {
    global $ProgramsettingEX, $ProgramsettingDAO, $Programsetting;
}
```

**Process Flow**:
1. **Collect Form Data**:
   ```php
   $programsettingsid = $_POST['programsettingsid'];
   $companyname = $_POST['companyname'];
   $address = $_POST['address'];
   $phone = $_POST['phone'];
   // ... other fields
   ```

2. **Process Logo Upload**:
   ```php
   $handle = new upload($_FILES['logo']);
   $image = updateImages($handle, "oldlogo", '../views/default/images/upload', 250, 250);
   ```

3. **Update Settings Object**:
   ```php
   $Programsetting->companyname = $companyname;
   $Programsetting->address = $address;
   $Programsetting->logo = $image;
   // ... other fields
   ```

4. **Save to Database**:
   ```php
   if (count($alldata) > 0) {
       $Programsetting->programsettingsid = 1;
       $ProgramsettingDAO->update($Programsetting);
   } else {
       $ProgramsettingDAO->insert($Programsetting);
   }
   ```

**Image Processing**:
- Logo upload handling
- Image resizing (250x250 pixels)
- Old image replacement
- Error handling for upload failures

---

## 🔄 Workflows

### Workflow 1: Settings Update Process
```
┌─────────────────────────────────────────────────────────────┐
│                START: Settings Update Request               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Collect Form Data                                       │
│     - Extract POST parameters                               │
│     - Validate required fields                              │
│     - Prepare data for processing                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Logo Upload                                     │
│     - Handle file upload                                    │
│     - Resize image to 250x250                               │
│     - Replace old logo file                                 │
│     - Update logo path                                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Settings Object                                  │
│     - Map form data to object properties                    │
│     - Set user ID and timestamp                             │
│     - Prepare for database operation                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save to Database                                        │
│     - Check if record exists                                │
│     - Update existing or insert new record                  │
│     - Handle database errors                                │
│     - Redirect to success page                              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display program settings form |
| `do=update` | `update()` | Process settings update |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Form Parameters (POST)
- `programsettingsid` - Settings record ID (always 1)
- `companyname` - Company name
- `address` - Company address
- `specializtion` - Business specialization
- `phone` - Phone number
- `faxnumber` - Fax number
- `email` - Email address
- `website` - Website URL
- `logo` - Logo file upload
- `roundnumbers` - Number rounding preference
- `saveprinting` - Save printing setting
- `deptprinting` - Department printing
- `printingpapersize` - Paper size
- `previousPrice` - Show previous prices
- `parcode` - Barcode settings
- `priceing` - Pricing method
- `lastprice` - Last price display
- `searchvalue` - Search configuration
- `updateproductprice` - Price update setting

---

## 🔒 Security & Permissions

### Access Control
```php
// Session-based user ID tracking
$userid = $_SESSION["userid"];
$Programsetting->userid = $_SESSION["userid"];
```

**Security Features**:
- Session-based authentication required
- User ID logging for audit trail
- File upload restrictions (images only)
- Input sanitization through framework

**Missing Security Features**:
- No explicit permission checking
- No CSRF protection
- No file type validation
- No input length limits

### File Upload Security
```php
$handle = new upload($_FILES['logo']);
$image = updateImages($handle, "oldlogo", '../views/default/images/upload', 250, 250);
```

**Upload Restrictions**:
- Image resizing to 250x250 pixels
- File replacement (not accumulation)
- Specific upload directory

---

## 📊 Performance Considerations

### Image Processing
- Automatic image resizing reduces file sizes
- Single logo file replacement (no duplicates)
- Cached image handling

### Database Operations
- Single record operations (programsettings ID = 1)
- Update vs Insert logic
- Minimal query overhead

### Optimization Opportunities
```php
// Consider adding validation
if (!empty($_FILES['logo']['tmp_name'])) {
    // Only process if new logo uploaded
    $image = updateImages($handle, "oldlogo", '../views/default/images/upload', 250, 250);
} else {
    // Keep existing logo
    $image = $alldata->logo;
}
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Logo Upload Failures**
**Issue**: Logo not updating after upload  
**Cause**: File upload errors or permission issues

**Debug**:
```php
// Check file upload errors
if ($_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
    echo "Upload error: " . $_FILES['logo']['error'];
}

// Check upload directory permissions
if (!is_writable('../views/default/images/upload')) {
    echo "Upload directory not writable";
}

// Debug image processing
print_r($handle); // Check upload handler
echo "Processed image: " . $image;
```

### 2. **Settings Not Saving**
**Issue**: Changes don't persist after update  
**Cause**: Database connection issues or transaction problems

**Debug**:
```php
// Check if record exists
$alldata = $ProgramsettingDAO->load(1);
echo "Existing record count: " . count($alldata);

// Debug the update operation
try {
    if (count($alldata) > 0) {
        $result = $ProgramsettingDAO->update($Programsetting);
    } else {
        $result = $ProgramsettingDAO->insert($Programsetting);
    }
    echo "Database operation result: " . $result;
} catch (Exception $e) {
    echo "Database error: " . $e->getMessage();
}
```

### 3. **Form Data Not Processing**
**Issue**: Posted data not reaching update function  
**Cause**: Form submission errors or routing issues

**Debug**:
```php
// Check POST data
echo "POST data received: ";
print_r($_POST);

// Verify form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "Form submitted via POST";
} else {
    echo "No POST data received";
}
```

### 4. **Image Size/Format Issues**
**Issue**: Images display incorrectly after upload  
**Cause**: Incorrect resizing or format conversion

**Fix**:
```php
// Add image validation
if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
    $imageInfo = getimagesize($_FILES['logo']['tmp_name']);
    if ($imageInfo === false) {
        throw new Exception('Invalid image file');
    }
    
    // Check image dimensions
    if ($imageInfo[0] > 2000 || $imageInfo[1] > 2000) {
        throw new Exception('Image too large');
    }
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Settings Update
```
1. Access settings form
2. Modify company information
3. Submit form
4. Verify changes saved
5. Check database record
```

### Test Case 2: Logo Upload
```
1. Select valid image file
2. Submit form with new logo
3. Verify image uploaded and resized
4. Check old logo replaced
5. Confirm logo displays correctly
```

### Test Case 3: Form Validation
```
1. Submit form with empty required fields
2. Test with invalid email format
3. Try uploading non-image files
4. Test with oversized images
5. Verify appropriate error handling
```

### Test Case 4: Permission Testing
```
1. Test with different user types
2. Verify session requirements
3. Check user ID logging
4. Test unauthorized access
```

---

## ⚠️ Security Recommendations

### Current Issues
1. **No Permission Checking**: Any logged-in user can modify settings
2. **No CSRF Protection**: Forms vulnerable to cross-site request forgery
3. **Weak File Validation**: Minimal file type checking
4. **No Input Limits**: Unlimited text input lengths

### Recommended Improvements
```php
// Add permission check
if (!hasPermission('manage_settings')) {
    throw new Exception('Insufficient permissions');
}

// Add CSRF protection
if (!verifyCsrfToken($_POST['csrf_token'])) {
    throw new Exception('Invalid request');
}

// Improve file validation
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['logo']['type'], $allowedTypes)) {
    throw new Exception('Invalid file type');
}

// Add input validation
if (strlen($_POST['companyname']) > 255) {
    throw new Exception('Company name too long');
}
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [programsettingsController.php](programsettingsController.md) - Main settings controller
- [login.php](login.md) - Authentication system
- [index.php](index.md) - Main dashboard

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Security Review**: ❌ Multiple security issues identified  
**Next Review**: When security improvements are implemented