# Maintenances Controller Documentation

**File**: `/controllers/maintenances.php`  
**Purpose**: Manages maintenance requests, tracking products sent for repair/warranty service  
**Last Updated**: December 20, 2024  
**Total Functions**: 13  
**Lines of Code**: ~491

---

## 📋 Overview

The Maintenances Controller manages the complete lifecycle of maintenance requests for products under warranty or repair. It handles:
- Creation and tracking of maintenance cases
- Product fault reporting and documentation
- Maintenance center and branch management
- Customer communication through comments
- Status tracking (warranty vs. repair)
- Integration with supplier warranty services
- Receipt and case management workflow

### Primary Functions
- [x] Create and manage maintenance requests
- [x] Track maintenance cases and statuses
- [x] Manage maintenance centers
- [x] Handle branch operations
- [x] Customer comment system
- [x] Dynamic data entry with AJAX
- [x] Status change tracking
- [x] Product defect documentation
- [x] Cost estimation and prepayment handling
- [x] Invoice and purchase date tracking

### Related Controllers
- [maintenancesends.php](maintenancesends.md) - Shipment tracking
- [maintenancesuppliers.php](maintenancesuppliers.md) - Supplier management
- [maintennanceArchiveController.php](maintennanceArchiveController.md) - Archive management
- [supplierController.php](#) - Supplier data
- [clientController.php](#) - Customer management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **maintenances** | Main maintenance records | id, clientid, supplierid, branchid, productid, maintenancecenterid, maintenancecaseid, receiptnumber, defect, accessories, estimatedcost, prepaid, conditions, userid |
| **maintenancecomments** | Comments on maintenance cases | id, maintenanceid, comments, userid, maintenancecommentdate, conditions |
| **maintenancecases** | Maintenance case types | id, casename, maintenancecasedate, userid, conditions |
| **maintenancecenters** | Service centers | id, centername, centerphone, centermobile, centeraddress, administrator, administratorphone, administratordebt, conditions |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer information | clientid, clientname, clientphone |
| **supplier** | Supplier/manufacturer data | supplierid, suppliername |
| **branch** | Branch locations | branchId, branchName, branchAddress, phone, mobile |
| **product** | Product catalog | productId, productName |
| **user** | System users | userid, employeename |

---

## 🔑 Key Functions

### 1. **Default Action** - Add New Maintenance
**Location**: Lines 21-26  
**Purpose**: Display form for creating new maintenance requests

**Process Flow**:
1. Assign current date and time to template
2. Set maintenance module flag for navigation
3. Display add form template

---

### 2. **show()** - Display All Maintenance Records
**Location**: Lines 26-36  
**Purpose**: Show maintenance listing with filtering and search capabilities

**Features**:
- Authentication required
- Load all active maintenance cases for dropdown
- YouTube tutorial links integration
- DataTables AJAX integration via `showajax()`

---

### 3. **edit()** - Edit Maintenance Record
**Location**: Lines 37-58  
**Purpose**: Edit existing maintenance record with comments

**Function Signature**:
```php
$id = filter_input(INPUT_GET, 'id');
$del = filter_input(INPUT_GET, 'del');
```

**Process Flow**:
1. Load maintenance data by ID
2. Get employee name from user table
3. Parse datetime for separate date/time fields
4. Load associated comments with employee names
5. Assign data to edit template

---

### 4. **savedata()** - Save/Update Maintenance Record
**Location**: Lines 213-298  
**Purpose**: Main function for saving maintenance requests with comments

**Function Signature**:
```php
function savedata()
```

**Process Flow**:
1. Validate and sanitize all input fields
2. Create new maintenance record or update existing
3. Set default maintenance case ID and policy ID
4. Loop through comments and save each one
5. Return JSON response with record ID

**Key Fields Handled**:
- Product ID, Supplier ID, Branch ID, Client ID
- Maintenance center and case assignments
- Receipt number and date/time
- Defect description and accessories
- Estimated cost and prepaid amount
- Purchase date, invoice number, and date
- Warranty vs. repair flag (`maintorguar`)

**Comment Handling**:
```php
for ($i = 1; $i <= $commentitr; $i++) {
    $maintenancecommentid = filter_input(INPUT_POST, 'maintenancecommentid_' . $i);
    $comments = filter_input(INPUT_POST, 'comments_' . $i);
    // Save each comment with maintenance ID
}
```

---

### 5. **savecomment()** - Individual Comment Management
**Location**: Lines 86-112  
**Purpose**: Save or update individual comments via AJAX

**Function Signature**:
```php
function savecomment()
```

**Process Flow**:
1. Get comment data and maintenance ID
2. Create new comment or update existing
3. Return JSON with comment ID and selection data

---

### 6. **savecase()** - Maintenance Case Management
**Location**: Lines 114-137  
**Purpose**: Create or update maintenance case types

**Function Signature**:
```php
function savecase()
```

**Process Flow**:
1. Validate case name input
2. Create new case or update existing
3. Return JSON response for dynamic dropdown updates

---

### 7. **savebranch()** - Branch Management
**Location**: Lines 140-167  
**Purpose**: Manage branch information for maintenance services

**Function Signature**:
```php
function savebranch()
```

**Process Flow**:
1. Collect branch details (name, phone, mobile, address)
2. Insert new branch or update existing via raw SQL
3. Return JSON with branch data for dropdown

**Database Operation**:
```php
R::exec("INSERT INTO `branch`(`branchName`, `branchDate`, `phone`, `mobile`, `branchNo`, `branchAddress`) 
         VALUES ('$branchName','$date','$phone','$mobile','$branchNo','$branchAddress')");
```

---

### 8. **savecenter()** - Maintenance Center Management
**Location**: Lines 170-210  
**Purpose**: Manage maintenance service centers

**Function Signature**:
```php
function savecenter()
```

**Process Flow**:
1. Collect center information and administrator details
2. Create or update maintenance center record
3. Optionally link to specific maintenance request
4. Return JSON response

**Center Data Fields**:
- Center name, phone, mobile, address
- Administrator name, phone, debt tracking

---

### 9. **showajax()** - DataTables AJAX Handler
**Location**: Lines 301-436  
**Purpose**: Provide server-side processing for maintenance listing table

**Function Signature**:
```php
function showajax()
```

**Filter Parameters**:
- `start_date` / `end_date` - Date range filtering
- `del` - Show deleted records
- `data1` - Supplier ID filter
- `data2` - Client ID filter
- `data3` - Branch ID filter
- `data4` - Warranty/repair type filter
- `data5` - Case ID filter

**Process Flow**:
1. Build dynamic WHERE clause based on filters
2. Add search functionality across multiple columns
3. Apply sorting and pagination
4. Join with related tables for display data
5. Generate action buttons based on record status

**SQL Query Structure**:
```sql
SELECT maintenances.*, employeename, clientname, suppliername, branchName, centername 
FROM maintenances 
LEFT JOIN user ON maintenances.userid = user.userid 
LEFT JOIN client ON maintenances.clientid = client.clientid 
LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
LEFT JOIN branch ON maintenances.branchid = branch.branchId  
LEFT JOIN maintenancecenters ON maintenances.maintenancecenterid = maintenancecenters.id
```

**Special Features**:
- Product name concatenation for multiple products
- Dynamic maintenance center assignment interface
- Conditional action buttons based on warranty type
- Comment editing interface in table cells

---

### 10. **changecase()** - Update Maintenance Case
**Location**: Lines 440-451  
**Purpose**: Change maintenance case status via AJAX

**Function Signature**:
```php
function changecase()
```

---

### 11. **changecenter()** - Update Maintenance Center
**Location**: Lines 454-465  
**Purpose**: Assign maintenance center to request

**Function Signature**:
```php
function changecenter()
```

---

### 12. **updatecomment()** - Update Comment Content
**Location**: Lines 467-486  
**Purpose**: Update comment text via inline editing

**Function Signature**:
```php
function updatecomment()
```

---

## 🔄 Workflows

### Workflow 1: New Maintenance Request Creation
```
┌─────────────────────────────────────────────────────────────┐
│                START: Create New Maintenance               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Fill Basic Information                                  │
│     - Select client, supplier, branch                      │
│     - Choose products needing maintenance                   │
│     - Enter receipt number and date                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Document Problem Details                                │
│     - Describe defect and symptoms                          │
│     - List accessories included                             │
│     - Add technical notes                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Cost and Warranty Information                           │
│     - Enter estimated repair cost                           │
│     - Record any prepayment made                           │
│     - Set warranty vs. repair type                         │
│     - Add purchase date and invoice info                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Add Comments (Optional)                                 │
│     - Multiple comments supported                           │
│     - Each comment tracked with user and timestamp          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Save and Track                                          │
│     - Generate maintenance ID                               │
│     - Set initial case status                              │
│     - Ready for center assignment                          │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Maintenance Case Management
```
┌─────────────────────────────────────────────────────────────┐
│               START: Maintenance Tracking                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initial Status (Case 1)                                │
│     - New maintenance request created                       │
│     - Awaiting center assignment                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Center Assignment                                       │
│     IF warranty (maintorguar = 1):                         │
│       │                                                     │
│       ├─→ Assign to maintenance center                     │
│       │   ├─ Select existing center                        │
│       │   └─ Create new center if needed                   │
│       │                                                     │
│     ELSE (warranty = 0):                                   │
│       └─→ Display "ضمان" (under warranty)                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Case Status                                      │
│     - Case 2: Sent to maintenance                          │
│     - Case 3: Work in progress                             │
│     - Case 4: Ready for pickup                             │
│     - Case 5: Completed                                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Communication & Updates                                 │
│     - Add progress comments                                 │
│     - Update cost estimates                                │
│     - Track completion status                              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add maintenance form |
| `do=show` | show() | Display maintenance listing |
| `do=edit` | edit() | Edit maintenance record |
| `do=savedata` | savedata() | Save/update maintenance |
| `do=showajax` | showajax() | DataTables AJAX data |
| `do=savecomment` | savecomment() | Save individual comment |
| `do=savecase` | savecase() | Save maintenance case type |
| `do=savebranch` | savebranch() | Save branch information |
| `do=savecenter` | savecenter() | Save maintenance center |
| `do=changecase` | changecase() | Update case status |
| `do=changecenter` | changecenter() | Update center assignment |
| `do=updatecomment` | updatecomment() | Update comment text |
| `do=appentcomment` | append template | Append comment form |

---

## 🧮 Calculation Methods

### Cost Tracking
```php
// Estimated cost calculation
$estimatedcost = filter_input(INPUT_POST, 'estimatedcost');
$prepaid = filter_input(INPUT_POST, 'prepaid');

// Remaining cost calculation (done on frontend)
$remaining = $estimatedcost - $prepaid;
```

### Maintenance Center Debt
```php
// Center administrator debt tracking
$administratordebt = filter_input(INPUT_POST, 'administratordebt');
// Stored for accounting purposes
```

---

## 🔒 Security & Permissions

### Input Sanitization
```php
// All inputs properly filtered
$productId = filter_input(INPUT_POST, 'product');
$supplierid = filter_input(INPUT_POST, 'supplier');
$receiptnumber = filter_input(INPUT_POST, 'receiptnumber');
```

### Authentication
- All modification actions require authentication
- Session-based user tracking
- User ID stored with all records

### Data Validation
- Required field validation on frontend
- Exception handling for database operations
- Conditional logic based on user permissions

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Needed**:
   - `maintenances(clientid, maintenancedate)`
   - `maintenances(supplierid, conditions)`
   - `maintenancecomments(maintenanceid, conditions)`

2. **Query Optimization**:
   - JOINs limited to necessary tables
   - Date filtering with proper indexing
   - Conditional loading of comments

### AJAX Performance
- Server-side pagination for large datasets
- Dynamic loading of related data
- Efficient search across multiple columns

---

## 🐛 Common Issues & Troubleshooting

### 1. **Maintenance Center Assignment Issues**
**Issue**: Cannot assign center to warranty items  
**Cause**: Logic prevents center assignment when `maintorguar = 0`

**Solution**: Check warranty flag before attempting assignment

### 2. **Comment Update Problems**
**Issue**: Comments not saving properly  
**Cause**: Missing CSRF validation or session expiry

**Debug**:
```sql
SELECT * FROM maintenancecomments WHERE maintenanceid = [ID] ORDER BY id DESC;
```

### 3. **Product Display Issues**
**Issue**: Product names not showing correctly  
**Cause**: Multiple product IDs stored as comma-separated string

**Fix**: Ensure proper parsing of product ID string:
```php
$products = R::getAll("SELECT productName FROM product WHERE productId in (".$row['productid'].")");
```

### 4. **Date/Time Handling**
**Issue**: DateTime splitting errors  
**Cause**: Inconsistent datetime format

**Fix**: Validate datetime before splitting:
```php
$new_time = explode(" ", $maintenancedata['dateatime']);
if (count($new_time) >= 2) {
    $smarty->assign('get_date', $new_time[0]);
    $smarty->assign('get_time', $new_time[1]);
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Maintenance Creation
```
1. Create new maintenance request with all required fields
2. Verify record saved with proper user ID and timestamp
3. Check maintenance case assignment
4. Confirm comment association
```

### Test Case 2: Warranty vs. Repair Workflow
```
1. Create warranty maintenance (maintorguar = 0)
2. Verify center assignment is disabled
3. Create repair maintenance (maintorguar = 1)
4. Verify center assignment interface appears
```

### Test Case 3: Comment System
```
1. Add multiple comments to maintenance record
2. Edit existing comment via inline editing
3. Verify user tracking and timestamps
4. Test comment deletion (soft delete)
```

### Test Case 4: AJAX Filtering
```
1. Test date range filtering
2. Filter by supplier, client, branch
3. Test search functionality
4. Verify pagination works correctly
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [maintenancesends.php](maintenancesends.md) - Shipment tracking
- [Database Schema Documentation](#) - Table relationships
- [API Documentation](#) - AJAX endpoints

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur