# Size Calculator Controller Documentation

**File**: `/controllers/sizecalculator.php`  
**Purpose**: Mathematical tool for calculating optimal piece cutting from boards/sheets  
**Last Updated**: December 21, 2024  
**Total Functions**: 1  
**Lines of Code**: ~94

---

## 📋 Overview

The Size Calculator Controller is a specialized mathematical utility tool designed for manufacturing and cutting optimization. It calculates the maximum number of pieces that can be cut from a larger board or sheet material by:
- Testing both orientations (normal and rotated)
- Calculating optimal cutting patterns
- Handling remainder space utilization
- Providing visual result comparison
- Optimizing material usage efficiency

This tool is particularly useful for:
- Woodworking and carpentry shops
- Sheet metal fabrication
- Glass cutting operations
- Textile pattern cutting
- Any manufacturing requiring efficient material utilization

### Primary Functions
- [x] Calculate pieces per board in normal orientation
- [x] Calculate pieces per board in rotated orientation  
- [x] Determine optimal orientation automatically
- [x] Handle remainder space optimization
- [x] Provide detailed cutting analysis
- [x] Display results with visual representation

### Related Controllers
- [productionController.php](#) - Production planning
- [materialController.php](#) - Material management
- [cuttingController.php](#) - Cutting operations

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| No database operations | This is a pure calculation tool | N/A |

### Supporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| None | Mathematical utility only | N/A |

---

## 🔑 Key Functions

### 1. **Default Action** - Calculator Form Display
**Location**: Line 38  
**Purpose**: Display size calculation input form

**Process Flow**:
1. Include authentication check
2. Display calculator input template
3. Set up form fields for board and piece dimensions

**Template**: `sizecalculatorview/calc.html`

---

### 2. **calc** - Perform Size Calculations
**Location**: Line 43  
**Purpose**: Calculate optimal cutting patterns and display results

**Function Signature**:
```php
// Parameters from POST
$boardDim1 = (float) filter_input(INPUT_POST, "boardDim1"); // Board length
$boardDim2 = (float) filter_input(INPUT_POST, "boardDim2"); // Board width  
$pieceDim1 = (float) filter_input(INPUT_POST, "pieceDim1"); // Piece length
$pieceDim2 = (float) filter_input(INPUT_POST, "pieceDim2"); // Piece width
```

**Process Flow**:
1. Extract and validate input dimensions
2. Calculate pieces using normal orientation: `calcSize(boardDim1, boardDim2, pieceDim1, pieceDim2)`
3. Calculate pieces using rotated orientation: `calcSize(boardDim1, boardDim2, pieceDim2, pieceDim1)`
4. Determine optimal orientation (highest piece count)
5. Assign results to template variables
6. Display results page

**Calculation Logic**:
```php
$r1 = calcSize($boardDim1, $boardDim2, $pieceDim1, $pieceDim2);  // Normal
$r2 = calcSize($boardDim1, $boardDim2, $pieceDim2, $pieceDim1);  // Rotated

$best = $r1;
if ($r2 > $r1) {
    $best = $r2;  // Choose orientation with more pieces
}
```

---

### 3. **calcSize()** - Core Calculation Algorithm
**Location**: Line 80  
**Purpose**: Calculate maximum pieces that fit in given board dimensions

**Function Signature**:
```php
function calcSize($a1, $b1, $a2, $b2) {
    // $a1, $b1 = board dimensions (length, width)
    // $a2, $b2 = piece dimensions (length, width)
}
```

**Algorithm Implementation**:
```php
function calcSize($a1, $b1, $a2, $b2) {
    // Primary cutting pattern
    $a4 = floor($a1 / $a2);  // How many pieces fit along board length
    $b4 = floor($b1 / $b2);  // How many pieces fit along board width  
    $c4 = $a4 * $b4;        // Total pieces in primary pattern
    
    // Remainder space utilization
    $b5 = $b1 - ($b4 * $b2);      // Remaining width after primary cuts
    $a8 = floor($a1 / $b2);       // Pieces in remainder (rotated)
    $b8 = floor($b5 / $a2);       // Pieces along remainder width
    $c8 = $a8 * $b8;              // Additional pieces from remainder
    
    return ($c4 + $c8);            // Total optimized pieces
}
```

---

## 🔄 Workflows

### Workflow 1: Size Calculation Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Material Cutting Calculation            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Input Board Dimensions                                  │
│     - Board Length (boardDim1)                             │
│     - Board Width (boardDim2)                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Input Piece Dimensions                                  │
│     - Piece Length (pieceDim1)                             │
│     - Piece Width (pieceDim2)                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Calculate Normal Orientation                            │
│     - Primary pattern: floor(boardLen/pieceLen) *          │
│                        floor(boardWidth/pieceWidth)        │
│     - Remainder space: Calculate additional pieces         │
│     - Result R1: Total pieces in normal orientation        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Calculate Rotated Orientation                           │
│     - Rotate piece 90 degrees                              │
│     - Primary pattern with swapped piece dimensions        │
│     - Remainder space optimization                          │
│     - Result R2: Total pieces in rotated orientation       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Determine Optimal Solution                              │
│     - Compare R1 vs R2                                      │
│     - Select orientation with maximum pieces               │
│     - Present both options and best choice                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Display Results                                         │
│     - Show pieces per orientation                           │
│     - Highlight optimal choice                              │
│     - Provide cutting pattern guidance                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default | Display size calculator input form |
| `do=calc` | `calcSize()` | Process calculations and show results |
| `do=sucess` | Success page | Display operation success message |
| `do=error` | Error page | Display operation error message |

### Required Parameters by Action

**Calculate** (`do=calc`):
- `boardDim1` - Board length dimension (float)
- `boardDim2` - Board width dimension (float)
- `pieceDim1` - Piece length dimension (float)
- `pieceDim2` - Piece width dimension (float)

### Template Variables Assigned

**Results Page**:
- `$dim1, $dim2` - Normal orientation piece dimensions
- `$r1` - Pieces count in normal orientation
- `$dim11, $dim22` - Rotated orientation piece dimensions  
- `$r2` - Pieces count in rotated orientation
- `$best` - Maximum pieces achievable (optimal choice)

---

## 🧮 Calculation Methods

### Primary Cutting Pattern Algorithm
```php
// Calculate how many pieces fit along each dimension
$a4 = floor($a1 / $a2);  // Pieces along board length
$b4 = floor($b1 / $b2);  // Pieces along board width
$c4 = $a4 * $b4;        // Total pieces in regular grid
```

### Remainder Space Optimization
```php
// Calculate remaining space after primary cuts
$b5 = $b1 - ($b4 * $b2);  // Unused width

// Try to fit rotated pieces in remainder space
$a8 = floor($a1 / $b2);   // Rotated pieces along length
$b8 = floor($b5 / $a2);   // Rotated pieces in remainder width
$c8 = $a8 * $b8;         // Additional pieces from remainder

// Total optimized cutting
return ($c4 + $c8);
```

### Orientation Comparison
```php
$r1 = calcSize($boardDim1, $boardDim2, $pieceDim1, $pieceDim2);  // Normal
$r2 = calcSize($boardDim1, $boardDim2, $pieceDim2, $pieceDim1);  // Rotated

$best = ($r2 > $r1) ? $r2 : $r1;  // Optimal orientation
```

### Example Calculation
```
Board: 120 cm × 80 cm
Piece: 30 cm × 25 cm

Normal Orientation:
- Primary: floor(120/30) × floor(80/25) = 4 × 3 = 12 pieces
- Remainder: 80 - (3×25) = 5 cm remaining width
- Additional: floor(120/25) × floor(5/30) = 4 × 0 = 0 pieces
- Total R1: 12 + 0 = 12 pieces

Rotated Orientation (25×30):
- Primary: floor(120/25) × floor(80/30) = 4 × 2 = 8 pieces  
- Remainder: 80 - (2×30) = 20 cm remaining width
- Additional: floor(120/30) × floor(20/25) = 4 × 0 = 0 pieces
- Total R2: 8 + 0 = 8 pieces

Best: 12 pieces (normal orientation)
```

---

## 🔒 Security & Permissions

### Authentication Requirements
- All actions require authentication via `include_once("../public/authentication.php")`
- Session-based access control

### Input Validation
```php
// Proper input filtering and type casting
$boardDim1 = (float) filter_input(INPUT_POST, "boardDim1");
$boardDim2 = (float) filter_input(INPUT_POST, "boardDim2");
$pieceDim1 = (float) filter_input(INPUT_POST, "pieceDim1");
$pieceDim2 = (float) filter_input(INPUT_POST, "pieceDim2");
```

### Mathematical Validation
- Uses `floor()` function for integer piece counts
- Prevents division by zero through positive dimension requirements
- Handles floating-point precision appropriately

---

## 📊 Performance Considerations

### Calculation Efficiency
1. **Algorithm Complexity**: O(1) - Constant time calculations
2. **Memory Usage**: Minimal - only stores dimension variables
3. **Processing Speed**: Very fast - simple mathematical operations

### Optimization Potential
```php
// Current implementation is already optimized for simplicity
// Could be enhanced with:
// 1. Multiple cutting pattern testing
// 2. Waste percentage calculations  
// 3. Cost optimization factors
// 4. Material grain direction considerations
```

### Scalability
- Pure mathematical tool - no database overhead
- Can handle very large dimension values
- Suitable for high-frequency calculations

---

## 🐛 Common Issues & Troubleshooting

### 1. **Division by Zero**
**Issue**: Application crash when piece dimensions are 0  
**Cause**: Missing input validation for zero values

**Prevention**:
```php
if ($pieceDim1 <= 0 || $pieceDim2 <= 0 || $boardDim1 <= 0 || $boardDim2 <= 0) {
    throw new Exception("All dimensions must be positive numbers");
}
```

### 2. **Piece Larger Than Board**
**Issue**: Calculations return 0 when piece exceeds board size  
**Cause**: Normal mathematical behavior but may confuse users

**Enhancement**:
```php
if ($pieceDim1 > $boardDim1 && $pieceDim2 > $boardDim2) {
    $message = "Piece dimensions exceed board size in both orientations";
}
```

### 3. **Floating Point Precision**
**Issue**: Unexpected results with very small decimal differences  
**Cause**: Floating point arithmetic precision

**Fix**:
```php
// Round dimensions to reasonable precision
$boardDim1 = round((float) filter_input(INPUT_POST, "boardDim1"), 2);
$boardDim2 = round((float) filter_input(INPUT_POST, "boardDim2"), 2);
```

### 4. **Template Display Issues**
**Issue**: Results not showing properly  
**Cause**: Template variable assignment errors

**Debug**:
```php
// Debug template assignments
echo "R1: $r1, R2: $r2, Best: $best";
$smarty->assign("debug_values", compact('r1', 'r2', 'best'));
```

---

## 🧪 Testing Scenarios

### Test Case 1: Perfect Fit Scenario
```
Board: 100 × 60
Piece: 20 × 15
Expected: 5 × 4 = 20 pieces (no waste)
Verify: Both orientations should be tested
```

### Test Case 2: Optimization Required
```
Board: 120 × 80  
Piece: 35 × 25
Normal: 3 × 3 = 9 pieces
Rotated: 4 × 2 = 8 pieces  
Expected: Best = 9 (normal orientation)
```

### Test Case 3: Remainder Space Utilization
```
Board: 100 × 50
Piece: 30 × 20
Primary: 3 × 2 = 6 pieces
Remainder: 50 - (2×20) = 10 cm
Additional: floor(100/20) × floor(10/30) = 5 × 0 = 0
Test both orientations and remainder calculations
```

### Test Case 4: Edge Cases
```
- Equal dimensions (square pieces on square boards)
- Piece larger than board in one dimension  
- Very small decimal dimensions
- Large dimension values (stress test)
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [Manufacturing Optimization](#) - Production planning tools
- [Mathematical Functions](#) - PHP mathematical operations
- [Template System](#) - Smarty template documentation

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When manufacturing optimization requirements change