# Size Color Controller Documentation

**File**: `/controllers/sizecolorController.php`  
**Purpose**: Manages product size and color attributes with image support  
**Last Updated**: December 21, 2024  
**Total Functions**: 4  
**Lines of Code**: ~220

---

## 📋 Overview

The Size Color Controller is a product attribute management module that handles size and color variations for products. It provides functionality for:
- Creating size and color attributes
- Type-based categorization (size vs color)
- Image upload for visual representation
- Soft delete functionality (conditions-based hiding)
- User tracking and audit trails
- Integration with product variant systems

### Primary Functions
- [x] Create size/color attributes with images
- [x] Edit existing attributes and update images
- [x] Soft delete attributes (hide from active use)
- [x] Display attribute listings with type filtering
- [x] Image upload and management
- [x] User audit tracking
- [x] Type-based categorization system

### Related Controllers
- [productController.php](#) - Product management
- [productVariantController.php](#) - Product variations
- [storeController.php](#) - Inventory management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **sizecolor** | Size/color attributes | sizecolorid, name, type, userid, conditions, image, sysdate |

### Supporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial video links | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Form Display
**Location**: Line 78  
**Purpose**: Display size/color attribute creation form

**Process Flow**:
1. Load add form template
2. Initialize form validation
3. Set up image upload fields

**Template**: `sizecolorview/add.html`

---

### 2. **add()** - Create New Size/Color Attribute
**Location**: Line 168  
**Purpose**: Process new size/color attribute creation with image upload

**Function Signature**:
```php
function add() {
    global $sizeColor;
    global $sizeColorDAO;
    
    $name = $_POST['name'];           // Attribute name
    $type = (int) $_POST['type'];     // Type: 0=size, 1=color
    $image = uploadnew('image', False, 0, 0, 'sizecolor');
}
```

**Process Flow**:
1. Extract POST data for attribute fields
2. Upload image using `uploadnew()` to 'sizecolor' folder
3. Create attribute object with all properties
4. Set system metadata (user, date, conditions)
5. Insert into database via DAO

**Attribute Object Setup**:
```php
$sizeColor->name = $name;
$sizeColor->type = $type;                    // 0=size, 1=color
$sizeColor->userid = $_SESSION['userid'];
$sizeColor->conditions = 0;                  // Active state
$sizeColor->image = $image;
$sizeColor->sysdate = date("Y-m-d");
$sizeColorDAO->insert($sizeColor);
```

---

### 3. **show** - Display Attribute Listings  
**Location**: Line 93  
**Purpose**: Show all active size/color attributes with management options

**Process Flow**:
1. Query all attributes with `conditions = 0` (active only)
2. Load YouTube tutorial links
3. Assign data to template for display
4. Enable custom check functionality

**Query Logic**:
```php
$allSizeColor = $sizeColorDAO->queryByConditions(0);  // Active only
$smarty->assign("allSizeColor", $allSizeColor);
```

**Template**: `sizecolorview/show.html`

---

### 4. **update()** - Edit Existing Attribute
**Location**: Line 201  
**Purpose**: Update attribute properties and optionally replace image

**Function Signature**:
```php
function update() {
    global $sizeColor;
    global $sizeColorDAO;
    
    $name = $_POST['name'];
    $type = (int) $_POST['type'];
    $id = (int) $_POST['id'];
    $image = uploadupdate('image', 'imageurl', False, 0, 0, 'sizecolor');
}
```

**Process Flow**:
1. Extract POST data including attribute ID
2. Handle image update using `uploadupdate()` - preserves existing if no new upload
3. Load existing attribute record
4. Update all modifiable fields
5. Save changes via DAO

**Update Logic**:
```php
$sizeColor = $sizeColorDAO->load($id);       // Load existing
$sizeColor->name = $name;
$sizeColor->type = $type;
$sizeColor->image = $image;                  // New or existing image
$sizeColorDAO->update($sizeColor);
```

---

### 5. **delete** - Soft Delete Attribute
**Location**: Line 104  
**Purpose**: Soft delete attribute by setting conditions flag

**Process Flow**:
1. Get attribute ID from URL parameter
2. Load existing attribute record
3. Set `conditions = 1` (hidden/deleted state)
4. Update record to hide from active use

**Soft Delete Logic**:
```php
$id = $_GET['id'];
$sizeColor = $sizeColorDAO->load($id);
$sizeColor->conditions = 1;                  // Mark as deleted
$sizeColorDAO->update($sizeColor);
```

**Note**: This is soft delete - records remain in database but hidden from normal operations.

---

## 🔄 Workflows

### Workflow 1: Size/Color Attribute Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Size/Color Attribute             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Add Form                                        │
│     - Load attribute creation template                      │
│     - Set up type selection (size/color)                   │
│     - Initialize image upload field                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission                                 │
│     - Extract name and type fields                          │
│     - Validate required data                                │
│     - Process image upload                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute add() Function                                  │
│     - Upload image to /upload/sizecolor/                   │
│     - Create size/color attribute object                   │
│     - Set audit fields (user, date)                        │
│     - Save to database via DAO                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Handle Success/Error                                    │
│     - Redirect to success page on completion               │
│     - Show error page if exception occurs                  │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Attribute Management Process
```
┌─────────────────────────────────────────────────────────────┐
│               START: Manage Attributes                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Attribute Listing                              │
│     - Query active attributes (conditions = 0)             │
│     - Load tutorial videos                                  │
│     - Show management interface                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Handle User Action                                      │
│     ┌─────────────────────┬─────────────────────────────────┐
│     │      EDIT           │         DELETE                  │
│     │                     │                                 │
│     │  ┌─────────────────┐│ ┌─────────────────────────────┐ │
│     │  │ Load edit form  ││ │ Set conditions = 1          │ │
│     │  │ with existing   ││ │ (soft delete)               │ │
│     │  │ data            ││ │                             │ │
│     │  └─────────────────┘│ └─────────────────────────────┘ │
│     └─────────────────────┴─────────────────────────────────┘
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Changes                                         │
│     - Handle image updates (preserve if no new upload)     │
│     - Update database records                               │
│     - Maintain audit trail                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Return to Listing                                       │
│     - Show updated attribute list                           │
│     - Display success/error messages                        │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default | Display attribute creation form |
| `do=add` | `add()` | Process new attribute creation |
| `do=show` | Display listing | Show all active attributes with management |
| `do=edit` | Edit form | Display attribute edit form with existing data |
| `do=update` | `update()` | Process attribute modifications |
| `do=delete` | Soft delete | Mark attribute as deleted (conditions = 1) |
| `do=sucess` | Success page | Display operation success message |
| `do=error` | Error page | Display operation error message |

### Required Parameters by Action

**Add Attribute** (`do=add`):
- `name` - Attribute name (e.g., "Red", "Large", "XL")
- `type` - Type integer (0=size, 1=color)
- `image` - Image file upload (optional)

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

**Update Attribute** (`do=update`):
- `id` - Attribute ID
- `name` - Updated attribute name
- `type` - Updated type
- `imageurl` - Current image URL (for update logic)
- `image` - New image file (optional)

**Delete Attribute** (`do=delete`):
- `id` - Attribute ID to soft delete

---

## 🧮 Calculation Methods

### Type Classification System
```php
// Type codes for attribute classification
$type = (int) $_POST['type'];
// 0 = Size attribute (Small, Medium, Large, XL, etc.)
// 1 = Color attribute (Red, Blue, Green, etc.)
```

### Image Upload Handling
```php
// New image upload (add function)
$image = uploadnew('image', False, 0, 0, 'sizecolor');
// Parameters: field_name, resize_flag, width, height, target_folder

// Update image upload (preserves existing if no new file)
$image = uploadupdate('image', 'imageurl', False, 0, 0, 'sizecolor');
// Handles: new_field, current_field, resize_flag, width, height, folder
```

### Soft Delete Logic
```php
// Active attributes query
$allSizeColor = $sizeColorDAO->queryByConditions(0);  // conditions = 0

// Soft delete implementation
$sizeColor->conditions = 1;  // Mark as deleted
$sizeColorDAO->update($sizeColor);
// Record remains in database but hidden from normal operations
```

### Audit Trail Implementation
```php
// System metadata tracking
$sizeColor->userid = $_SESSION['userid'];      // Who created/modified
$sizeColor->sysdate = date("Y-m-d");          // When created/modified
$sizeColor->conditions = 0;                    // Status flag
```

---

## 🔒 Security & Permissions

### Authentication Requirements
- All actions require authentication via `include_once("../public/authentication.php")`
- Session-based user validation
- User ID tracking for audit purposes

### Input Sanitization
```php
// Type casting for security
$type = (int) $_POST['type'];     // Ensure integer type
$id = (int) $_POST['id'];         // Ensure integer ID

// Direct POST access - relies on framework filtering
$name = $_POST['name'];           // Should be sanitized at framework level
```

### File Upload Security
- Upload functions provide built-in security
- File type validation in upload library
- Path traversal prevention
- Target folder restriction to 'sizecolor'

### SQL Injection Prevention
- Uses DAO layer with prepared statements
- Object-based database operations
- No direct SQL concatenation

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `sizecolor(conditions)` for active/deleted filtering
   - `sizecolor(type)` for size/color type filtering
   - `sizecolor(userid)` for user-based queries

2. **Query Efficiency**:
   - Soft delete filtering at database level
   - Type-based categorization
   - Efficient DAO-based operations

3. **File Storage**:
   - Images stored in organized `/upload/sizecolor/` directory
   - No automatic resizing - consider for large images
   - File cleanup not implemented for soft deletes

### Known Performance Issues
```php
// No pagination in show() function
$allSizeColor = $sizeColorDAO->queryByConditions(0);
// May become slow with thousands of attributes

// Missing file cleanup for soft deletes
// Files remain on disk even when attributes are "deleted"
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Type Classification Confusion**
**Issue**: Unclear distinction between size and color types  
**Cause**: No validation of type field values

**Debug**:
```php
// Check type distribution
SELECT type, COUNT(*) FROM sizecolor GROUP BY type;

// Validate type values
if (!in_array($type, [0, 1])) {
    throw new Exception("Invalid type: must be 0 (size) or 1 (color)");
}
```

### 2. **Image Upload Failures**
**Issue**: Images not uploading or updating properly  
**Cause**: Directory permissions or file size limits

**Fix**:
```php
// Check upload directory
if (!is_writable('../upload/sizecolor/')) {
    chmod('../upload/sizecolor/', 0755);
}

// Debug upload function
$image = uploadnew('image', False, 0, 0, 'sizecolor');
if (empty($image)) {
    error_log("Image upload failed");
}
```

### 3. **Soft Delete Recovery**
**Issue**: No way to recover soft-deleted attributes  
**Cause**: Missing "restore" functionality

**Solution**:
```php
// Add restore function
function restore($id) {
    global $sizeColorDAO;
    $sizeColor = $sizeColorDAO->load($id);
    $sizeColor->conditions = 0;  // Restore to active
    $sizeColorDAO->update($sizeColor);
}
```

### 4. **Orphaned Files**
**Issue**: Image files remain after soft delete  
**Cause**: No file cleanup in delete function

**Fix**:
```php
// Implement file cleanup in delete function
if (!empty($sizeColor->image) && file_exists('../upload/sizecolor/' . $sizeColor->image)) {
    // Consider moving to archive instead of deleting
    rename(
        '../upload/sizecolor/' . $sizeColor->image,
        '../upload/sizecolor/deleted/' . $sizeColor->image
    );
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Size Attribute Creation
```
1. Access attribute add form
2. Enter size name "Large"
3. Select type = 0 (size)
4. Upload representative image
5. Submit and verify database entry
6. Check file exists in /upload/sizecolor/
```

### Test Case 2: Color Attribute Management
```
1. Create color attribute "Red" with type = 1
2. Edit to change name to "Crimson Red"
3. Upload new color swatch image
4. Verify old image handling
5. Test soft delete functionality
```

### Test Case 3: Type Filtering
```
1. Create multiple size attributes (S, M, L, XL)
2. Create multiple color attributes (Red, Blue, Green)
3. Query by type and verify separation
4. Test in product variant association
```

### Test Case 4: Soft Delete and Recovery
```
1. Create test attribute
2. Perform soft delete (conditions = 1)
3. Verify hidden from show listing
4. Check database record still exists
5. Test manual recovery if implemented
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [File Upload Library](#) - Upload function documentation
- [Product Variants](#) - How sizes/colors link to products
- [DAO Pattern Documentation](#) - Database access pattern

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When product variant system changes occur