# Stage Property Controller Documentation

**File**: `/controllers/stagepropertyController.php`  
**Purpose**: Manages maintenance/production stage properties with value tracking and cost analysis  
**Last Updated**: December 21, 2024  
**Total Functions**: 7  
**Lines of Code**: ~372

---

## 📋 Overview

The Stage Property Controller is a specialized maintenance and production management module that handles stage-specific properties and their associated values. It's designed for tracking characteristics, parameters, and costs related to maintenance or production stages. The system provides:
- Stage property definition and management
- Initial value assignment and tracking
- Cost aggregation and analysis
- Branch-based property management
- Property filtering by stage
- Soft delete functionality with audit trails
- User and date tracking for all operations

This controller is particularly useful for:
- Maintenance procedure standardization
- Production stage parameter tracking
- Cost analysis for stage operations
- Resource requirement documentation
- Quality control parameter definition

### Primary Functions
- [x] Create stage properties with initial values
- [x] Edit property definitions and values
- [x] Soft delete properties with recovery
- [x] Display properties filtered by stage
- [x] Calculate total costs per stage
- [x] Branch-based property management
- [x] User audit tracking
- [x] Cost aggregation and reporting

### Related Controllers
- [stageController.php](#) - Main production stage management
- [maintenanceController.php](#) - Maintenance operations
- [productionController.php](#) - Production management
- [branchController.php](#) - Branch management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **m_stageproperity** | Stage property definitions | stageProperityId, stageId, name, initialValue, stageProperityDate, userId, branchId, del |
| **m_stage** | Stage master data | stageId, title |

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

---

## 🔑 Key Functions

### 1. **Default Action** - Add Property Form
**Location**: Line 57  
**Purpose**: Display stage property creation form

**Process Flow**:
1. Include authentication check
2. Load all available stages for selection
3. Set up maintenance-specific header
4. Display property add form

**UI Setup**:
```php
$allstage = getstage();    // Load available stages

// Maintenance header setup
$smarty->assign("title1", 'الصيانة');           // Arabic: Maintenance
$smarty->assign("title2", 'خواص المراحل');      // Arabic: Stage Properties  
$smarty->assign("title3", 'اضافة خواص المراحل'); // Arabic: Add Stage Properties
$smarty->assign("link", 'stagepropertyController.php?do=show');
```

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

---

### 2. **add()** - Create New Stage Property
**Location**: Line 240  
**Purpose**: Create stage property with initial value and metadata

**Function Signature**:
```php
function add() {
    global $MStageproperityDAO, $MStageproperity;
}
```

**Process Flow**:
1. Extract property details from POST data
2. Set hardcoded stage ID (currently fixed to 2)
3. Create property record with branch and user tracking
4. Set deletion flag to 0 (active)

**Property Creation**:
```php
$propertyname = $_POST['propertyname'];
$stagename = 2;  // Fixed stage ID - hardcoded
$stagevalue = $_POST['stagevalue'];

$MStageproperity->stageId = $stagename;
$MStageproperity->initialValue = $stagevalue;
$MStageproperity->name = $propertyname;
$MStageproperity->stageProperityDate = date("y-m-d");      // Note: 2-digit year
$MStageproperity->userId = $_SESSION['userid'];
$MStageproperity->branchId = $_SESSION['branchId'];
$MStageproperity->del = 0;                                 // Active status

$MStageproperityDAO->insert($MStageproperity);
```

---

### 3. **show()** - Display Properties with Cost Analysis
**Location**: Line 264  
**Purpose**: Show stage properties with filtering and cost totals

**Function Signature**:
```php
function show($stageid) {
    global $MStageproperity, $MStageproperityEX;
    global $MStageDAO, $smarty;
}
```

**Process Flow**:
1. Build dynamic query string based on stage filter
2. Handle special cases (all stages, specific stage)
3. Execute property query with filters
4. Calculate total cost for displayed properties
5. Assign data and totals to template

**Dynamic Query Building**:
```php
$queryString = ' WHERE';

if (isset($stageid) && $stageid != '-1' && $stageid != "-2") {
    // Specific stage
    $stagename = $MStageDAO->load($stageid);
    $message = " اسم المرحله " . $stagename->title;  // Arabic: Stage name
    $queryString .= '  m_stageproperity.stageId = ' . $stageid . ' AND';
}

if (isset($stageid) && $stageid != "-1" && $stageid == "-2") {
    // All stages
    $message = " كل المراحل";                        // Arabic: All stages
    $queryString .= '  m_stageproperity.stageId > 0  AND';
}
```

**Cost Calculation**:
```php
$cost = 0;
foreach ($showndata as $stagedata) {
    $cost += $stagedata->initialValue;
}
$smarty->assign("showndata", $showndata);
$smarty->assign("cost", $cost);
```

---

### 4. **update()** - Edit Existing Property
**Location**: Line 332  
**Purpose**: Update property name, value, and metadata

**Function Signature**:
```php
function update() {
    global $MStageproperityDAO, $MStageproperity;
}
```

**Process Flow**:
1. Extract updated property details
2. Load existing property record
3. Update all modifiable fields
4. Maintain audit trail with user/date

**Update Logic**:
```php
$propertyname = $_POST['propertyname'];
$stagename = 2;  // Still hardcoded to stage 2
$stagevalue = $_POST['stagevalue'];
$propertyid = $_POST['propertyid'];

$MStageproperity->stageProperityId = $propertyid;
$MStageproperity->stageId = $stagename;
$MStageproperity->initialValue = $stagevalue;
$MStageproperity->name = $propertyname;
$MStageproperity->stageProperityDate = date("y-m-d");
$MStageproperity->userId = $_SESSION['userid'];
$MStageproperity->branchId = $_SESSION['branchId'];
$MStageproperity->del = 0;

$MStageproperityDAO->update($MStageproperity);
```

---

### 5. **delete()** - Soft Delete Property
**Location**: Line 355  
**Purpose**: Mark property as deleted without removing data

**Function Signature**:
```php
function delete() {
    global $MStageproperityEX, $MStageproperity;
}
```

**Process Flow**:
1. Get property ID from URL parameter
2. Set deletion flag to 1 (deleted)
3. Update with current user and date
4. Use extended DAO for soft delete operation

**Soft Delete Logic**:
```php
$id = $_GET['id'];
$MStageproperity->stageProperityId = $id;
$MStageproperity->stageProperityDate = date("y-m-d");
$MStageproperity->userId = $_SESSION['userid'];
$MStageproperity->branchId = $_SESSION['branchId'];
$MStageproperity->del = 1;                           // Mark as deleted

$MStageproperityEX->updatestage($MStageproperity);   // Soft delete
```

---

### 6. **edit()** - Load Property for Editing
**Location**: Line 323  
**Purpose**: Retrieve property data for edit form display

**Function Signature**:
```php
function edit() {
    global $MStageproperityEX;
    
    $id = $_GET['id'];
    $alldata = $MStageproperityEX->loadstage($id);
    return $alldata;
}
```

---

### 7. **getstage()** - Load Available Stages
**Location**: Line 227  
**Purpose**: Retrieve all available stages for selection dropdown

**Function Signature**:
```php
function getstage() {
    global $MStageDAO;
    $allstage = $MStageDAO->queryAll();
    return $allstage;
}
```

---

## 🔄 Workflows

### Workflow 1: Stage Property Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Stage Property                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Property Creation Form                          │
│     - Load available stages (getstage())                   │
│     - Set up maintenance UI headers                         │
│     - Display property input fields                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Input Property Details                                  │
│     - Enter property name/description                       │
│     - Set initial value (cost/parameter)                    │
│     - Stage ID automatically set to 2 (hardcoded)          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute add() Function                                  │
│     - Extract POST data                                      │
│     - Create property record with metadata                  │
│     - Set branch and user tracking                          │
│     - Insert into m_stageproperity table                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Handle Success/Error                                    │
│     - Redirect to success page on completion               │
│     - Show error page if exception occurs                  │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Property Display and Cost Analysis
```
┌─────────────────────────────────────────────────────────────┐
│               START: View Stage Properties                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Access Property Listing                                │
│     - Load maintenance header interface                     │
│     - Set up stage filtering options                        │
│     - Call show() with stage ID parameter                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Build Dynamic Query                                     │
│     - Determine stage filter (specific/all)                │
│     - Build WHERE clause dynamically                        │
│     - Handle query string cleanup                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute Query and Calculate Totals                     │
│     - Query m_stageproperity with filters                  │
│     - Loop through results                                  │
│     - Sum all initialValue fields                           │
│     - Prepare data for template                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Display Results with Cost Summary                      │
│     - Show properties in table format                       │
│     - Display total cost calculation                        │
│     - Provide edit/delete action buttons                    │
│     - Show stage name context                               │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default | Display property creation form |
| `do=add` | `add()` | Process new property creation |
| `do=show` | `show(2)` | Display properties (hardcoded to stage 2) |
| `do=edit` | `edit()` | Display property edit form |
| `do=editprint` | Edit print | Display printable edit form |
| `do=update` | `update()` | Process property modifications |
| `do=delete` | `delete()` | Soft delete property |
| `do=sucess` | Success page | Display operation success message |
| `do=error` | Error page | Display operation error message |

### Required Parameters by Action

**Add Property** (`do=add`):
- `propertyname` - Property name/description
- `stagevalue` - Initial value (cost/parameter value)

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

**Update Property** (`do=update`):
- `propertyid` - Property ID
- `propertyname` - Updated property name
- `stagevalue` - Updated value

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

### Template Variables Assigned

**Show Properties**:
- `$showndata` - Property records matching filter
- `$cost` - Total cost of all displayed properties
- `$message` - Stage name context message

**Headers** (for maintenance UI):
- `$title1` - Main title (الصيانة - Maintenance)
- `$title2` - Section title (خواص المراحل - Stage Properties)
- `$title3` - Action title (varies by action)

---

## 🧮 Calculation Methods

### Cost Aggregation
```php
// Sum all property values for cost analysis
$cost = 0;
foreach ($showndata as $stagedata) {
    $cost += $stagedata->initialValue;
}
$smarty->assign("cost", $cost);
```

### Dynamic Query Building
```php
$queryString = ' WHERE';

// Add stage filter
if (isset($stageid) && $stageid != '-1' && $stageid != "-2") {
    $queryString .= '  m_stageproperity.stageId = ' . $stageid . ' AND';
}

// Clean up query string
$arr = explode(' ', $queryString);
if (isset($arr) && count($arr) > 0) {
    $lastWord = end($arr);
    if ($lastWord == 'AND') {
        array_pop($arr);                           // Remove trailing AND
        $queryString = implode(' ', $arr);
    } else if ($lastWord == 'WHERE') {
        array_pop($arr);                           // Remove empty WHERE
        $queryString = ' ';
    }
}
```

### Hardcoded Stage Logic
```php
// Stage ID currently hardcoded to 2 in multiple functions
$stagename = 2;  // This should be dynamic in production systems

// Show function called with hardcoded parameter
show(2);  // Always shows stage 2 properties
```

### Date Formatting
```php
// Note: Uses 2-digit year format
$MStageproperity->stageProperityDate = date("y-m-d");  // YY-MM-DD format
// Consider changing to full 4-digit year: date("Y-m-d")
```

---

## 🔒 Security & Permissions

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

### Input Sanitization
```php
// Direct POST access - framework-level sanitization expected
$propertyname = $_POST['propertyname'];
$stagevalue = $_POST['stagevalue'];
$propertyid = $_POST['propertyid'];

// URL parameter access
$id = $_GET['id'];  // Should be validated as integer
```

### Branch-Based Security
```php
// All operations track branch association
$MStageproperity->branchId = $_SESSION['branchId'];

// Could be used for branch-based access control
// (Currently not implemented but data structure supports it)
```

### Audit Trail
```php
// User and date tracking for all modifications
$MStageproperity->userId = $_SESSION['userid'];
$MStageproperity->stageProperityDate = date("y-m-d");

// Soft delete preserves audit trail
$MStageproperity->del = 1;  // Mark deleted, don't remove
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `m_stageproperity(stageId, del)` for stage filtering
   - `m_stageproperity(del)` for active/deleted filtering
   - `m_stageproperity(branchId)` for branch-based queries
   - `m_stageproperity(userId)` for user-based filtering

2. **Query Efficiency**:
   - Single query with filters vs multiple queries
   - Cost calculation at application level (consider database aggregation)
   - Efficient WHERE clause building

3. **Data Volume Considerations**:
   - No pagination implemented - may be slow with many properties
   - Consider limits for large datasets

### Known Performance Issues
```php
// Cost calculation in application loop
foreach ($showndata as $stagedata) {
    $cost += $stagedata->initialValue;
}
// Could be optimized with database SUM() aggregation

// Hardcoded stage limitations
show(2);  // Only shows one stage - limits scalability

// No result set limiting
$showndata = $MStageproperityEX->queryAllproperty($queryString);
// May return large datasets without pagination
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Hardcoded Stage Limitation**
**Issue**: All operations fixed to stage ID 2  
**Cause**: Hardcoded stage assignment in add() and update()

**Fix**:
```php
// Replace hardcoded stage with dynamic selection
// $stagename = 2;  // Remove this line
$stagename = $_POST['stagename'];  // Add stage selection to form

// Update show() to accept dynamic stage parameter
// show(2);  // Replace with
$stageid = $_REQUEST['stageid'] ?? -1;
show($stageid);
```

### 2. **Year Format Issue**
**Issue**: 2-digit year format may cause confusion  
**Cause**: `date("y-m-d")` uses 2-digit year

**Fix**:
```php
// Change to 4-digit year format
$MStageproperity->stageProperityDate = date("Y-m-d");  // Full year
```

### 3. **Query String Building Issues**
**Issue**: Malformed SQL WHERE clauses  
**Cause**: Complex string manipulation without validation

**Debug**:
```php
// Debug query string building
echo "Query String: " . $queryString . "<br>";

// Validate final query
if (trim($queryString) == 'WHERE') {
    $queryString = '';  // Empty WHERE clause
}
```

### 4. **Missing Stage Selection**
**Issue**: No way to select different stages  
**Cause**: Hardcoded stage ID and show() parameter

**Enhancement**:
```php
// Add stage selection to form and show function
if (isset($_REQUEST['stageid'])) {
    $selectedStage = $_REQUEST['stageid'];
    show($selectedStage);
} else {
    show(-2);  // Show all stages by default
}
```

### 5. **Cost Calculation Accuracy**
**Issue**: Cost totals may not reflect filtered results  
**Cause**: Currency/decimal precision handling

**Fix**:
```php
// Improve cost calculation with proper formatting
$cost = 0;
foreach ($showndata as $stagedata) {
    $cost += (float) $stagedata->initialValue;
}
$cost = round($cost, 2);  // Round to 2 decimal places
$smarty->assign("cost", number_format($cost, 2));
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Property Creation
```
1. Access property add form
2. Enter property name "Lubrication Cost"
3. Set value 25.50
4. Submit and verify database entry
5. Check branch and user tracking
6. Verify stage ID assignment (currently 2)
```

### Test Case 2: Property Display and Filtering
```
1. Create multiple properties for different stages
2. Access property listing (show function)
3. Verify cost calculation accuracy
4. Test stage filtering (currently limited to stage 2)
5. Check Arabic text display
```

### Test Case 3: Property Update
```
1. Edit existing property
2. Change name and value
3. Verify update preserves metadata
4. Check audit trail (user, date)
5. Verify cost totals update correctly
```

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

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [Maintenance Management](#) - Overall maintenance system
- [Stage Management](#) - Production stage definitions
- [Branch Management](#) - Multi-branch operations

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When maintenance management requirements change