# Cost Center Controller Documentation

**File**: `/controllers/costcenterController.php`  
**Purpose**: Manages cost centers for expense allocation and project tracking with CRUD operations and bulk actions  
**Last Updated**: December 20, 2024  
**Total Functions**: 9  
**Lines of Code**: ~449

---

## 📋 Overview

The Cost Center Controller provides comprehensive management of cost centers used for expense allocation, project tracking, and departmental budgeting. It includes standard CRUD operations, soft delete functionality, bulk operations, and referential integrity checking.

### Primary Functions
- [x] Add new cost centers
- [x] View and list all cost centers
- [x] Edit existing cost centers
- [x] Soft delete with referential integrity checks
- [x] Restore deleted cost centers
- [x] Bulk operations (delete/restore multiple items)
- [x] Dependency validation before deletion
- [x] User permission integration

### Related Controllers
- [costcenterReportController.php](costcenterReportController.md) - Cost center reporting
- [expensesController.php](#) - Expense management
- [projectController.php](#) - Project management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **costcenter** | Cost center definitions | id, name, comment, condation, userid |
| **costcenterdetail** | Cost center transaction details | costcenterdetailid, costcenterid, costdate |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username, employeename |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Form Display
**Location**: Line 59  
**Purpose**: Display cost center creation form

**Function Signature**:
```php
// Triggered when: empty($do)
```

**Process Flow**:
1. Display header template
2. Show cost center add form (`add.html`)
3. Include custom validation scripts

---

### 2. **add** - Create New Cost Center
**Location**: Line 226  
**Purpose**: Insert new cost center record

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

**Process Flow**:
1. Retrieve form data (name, description)
2. Create new Costcenter object
3. Set default values and user ID
4. Insert into database
5. Redirect to success page

**Implementation**:
```php
$name = $_POST['name'];
$descripe = $_POST['descripe'];

$Costcenter->name = $name;
$Costcenter->condation = 0; // Active status
$Costcenter->comment = $descripe;
$Costcenter->userid = $_SESSION['userid'];

$CostcenterDAO->insert($Costcenter);
```

---

### 3. **show** - Display Cost Centers List
**Location**: Line 246  
**Purpose**: Show all cost centers in data table

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

**Process Flow**:
1. Query all cost center records
2. Assign data to template
3. Display with custom checkbox functionality

**Implementation**:
```php
$qname = $CostcenterDAO->queryAll();
$smarty->assign('name', $qname);
```

---

### 4. **edit** - Load Edit Form
**Location**: Line 261  
**Purpose**: Load existing cost center for editing

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

**Process Flow**:
1. Get cost center ID from URL
2. Load existing record
3. Return data for form population

**Implementation**:
```php
$id = $_GET['id'];
$data = $CostcenterDAO->load($id);
return $data;
```

---

### 5. **update** - Update Cost Center
**Location**: Line 275  
**Purpose**: Update existing cost center record

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

**Process Flow**:
1. Retrieve updated form data
2. Set cost center properties
3. Execute update operation
4. Redirect to success

**Implementation**:
```php
$id = $_POST['id'];
$name = $_POST['name'];
$descripe = $_POST['descripe'];

$Costcenter->name = $name;
$Costcenter->del = 0;
$Costcenter->comment = $descripe;
$Costcenter->id = $id;

$CostcenterDAO->update($Costcenter);
```

---

### 6. **delete** - Soft Delete with Validation
**Location**: Line 299  
**Purpose**: Safely delete cost center with referential integrity checks

**Function Signature**:
```php
function delete($id)
```

**Process Flow**:
1. Check for dependent cost center details
2. If dependencies exist, prevent deletion
3. If safe, mark as deleted (soft delete)
4. Return operation status

**Dependency Check**:
```php
$alldata = $CostcenterdetailDAO->queryByCostcenterid($id);

if(count($alldata) > 0) {
    $note = "لا يمكن حذف هذا النوع لانه مرتبط ببيانات اخرى";
} else {
    $Costcenter->id = $id;
    $Costcenter->condation = 1; // Mark as deleted
    $CostcenterEX->updatedel($Costcenter);
    $note = "sucess";
}
```

---

### 7. **ruturndelete** - Restore Deleted Cost Center
**Location**: Line 338  
**Purpose**: Restore a previously soft-deleted cost center

**Function Signature**:
```php
function ruturndelete($id)
```

**Process Flow**:
1. Validate cost center was previously deleted
2. Reset deletion status
3. Return operation result

**Implementation**:
```php
$Costcenter->id = $id;
$Costcenter->condation = 0; // Mark as active
if($CostcenterEX->updatedel($Costcenter)) {
    $note = "sucess";
} else {
    $note = "لم تتم العمليه بنجاح لان هذا العنصر لم يتم حذف من قبل ";
}
```

---

### 8. **execute** - Bulk Operations
**Location**: Line 373  
**Purpose**: Perform bulk delete/restore operations

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

**Process Flow**:
1. Get operation type (1=delete, 2=restore)
2. Get array of selected cost center IDs
3. Loop through each ID and perform operation
4. Collect and display results for failed operations

**Bulk Processing**:
```php
$operationType = $_POST['operation'];
$choosedItemArr = $_POST['choosedItem'];

foreach($choosedItemArr as $costcenterid) {
    $costcenterdata = $CostcenterDAO->load($costcenterid);
    $cattitel = $costcenterdata->name;
    
    if($operationType == '1') {
        $note = delete($costcenterid); // Bulk delete
    } elseif($operationType == "2") {
        $note = ruturndelete($costcenterid); // Bulk restore
    }
    
    // Collect failed operations
    if($note != "sucess") {
        $outputString .= $cattitel. ": ".$note."<br/>";
    }
}
```

---

## 🔄 Workflows

### Workflow 1: Cost Center Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: User Creates Cost Center               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Fill Cost Center Details                                │
│     - Enter cost center name                                │
│     - Add description/comment                               │
│     - System auto-assigns user ID                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Validate Input                                          │
│     - Check required fields                                 │
│     - Validate name uniqueness (business rule)             │
│     - Ensure proper character encoding                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Save Cost Center                                        │
│     - Set condation = 0 (active)                           │
│     - Record creation user and timestamp                    │
│     - Insert into costcenter table                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Confirmation                                            │
│     - Display success message                               │
│     - Return to cost center list                           │
│     - Available for expense allocation                      │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Safe Deletion Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: User Attempts Deletion                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Check Dependencies                                      │
│     - Query costcenterdetail table                         │
│     - Count related expense records                         │
│     - Verify no active allocations                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Decision Point                                          │
│     ┌─────────────────────┬─────────────────────────────────┐ │
│     │  DEPENDENCIES EXIST │    NO DEPENDENCIES             │ │
│     └─────────────────────┼─────────────────────────────────┘ │
└─────────────────────────────┬─────────────────────────────────┘
                             │                     │
                             ▼                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3a. Block Deletion                                         │
│     - Display error message                                 │
│     - Show dependency details                               │
│     - Suggest removing dependencies first                   │
│     - Return to cost center list                           │
└─────────────────────────────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────┐
│  3b. Perform Soft Delete                                    │
│     - Set condation = 1 (deleted)                          │
│     - Preserve record for audit purposes                    │
│     - Hide from active lists                               │
│     - Allow future restoration                             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Show add form |
| `do=add` | `add()` | Create new cost center |
| `do=show` | `show()` | Display cost centers list |
| `do=edit` | `edit()` | Load edit form |
| `do=update` | `update()` | Update cost center |
| `do=delete` | `delete()` | Soft delete cost center |
| `do=ruturndelete` | `ruturndelete()` | Restore deleted cost center |
| `do=executeOperation` | `execute()` | Bulk operations |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Required Parameters by Action

**Add** (`do=add`):
- `name` - Cost center name
- `descripe` - Description/comment

**Edit** (`do=edit`):
- `id` - Cost center ID

**Update** (`do=update`):
- `id` - Cost center ID
- `name` - Updated name
- `descripe` - Updated description

**Delete/Restore** (`do=delete`, `do=ruturndelete`):
- `id` - Cost center ID

**Bulk Operations** (`do=executeOperation`):
- `operation` - Operation type (1=delete, 2=restore)
- `choosedItem[]` - Array of selected IDs

---

## 🔒 Security & Permissions

### User Tracking
```php
$Costcenter->userid = $_SESSION['userid']; // Track creator
```

### Input Validation
```php
$name = $_POST['name'];      // Cost center name
$descripe = $_POST['descripe']; // Description
$id = $_POST['id'];          // For updates
```

### Referential Integrity
- Checks dependencies before deletion
- Prevents orphaned cost center details
- Maintains data consistency

### Session Management
- Requires active user session
- Tracks user actions for audit

---

## 🐛 Common Issues & Troubleshooting

### 1. **Cannot Delete Cost Center**
**Issue**: Deletion blocked with dependency message  
**Cause**: Active cost center details exist

**Debug**:
```sql
SELECT COUNT(*) as detail_count 
FROM costcenterdetail 
WHERE costcenterid = [ID];
```

**Solution**: Remove or reassign cost center details before deletion

### 2. **Bulk Operation Failures**
**Issue**: Some items in bulk operation fail  
**Cause**: Mixed dependency status

**Debug**:
```php
// Check individual item status
foreach($choosedItemArr as $id) {
    $details = $CostcenterdetailDAO->queryByCostcenterid($id);
    echo "ID $id has " . count($details) . " dependencies<br>";
}
```

### 3. **Restore Operation Fails**
**Issue**: Cannot restore previously deleted cost center  
**Cause**: Item was not actually deleted or already active

**Debug**:
```sql
SELECT id, name, condation FROM costcenter WHERE id = [ID];
-- condation: 0 = active, 1 = deleted
```

---

## 🧪 Testing Scenarios

### Test Case 1: Normal CRUD Operations
```
1. Create new cost center with valid data
2. Verify cost center appears in list
3. Edit cost center details
4. Update and verify changes
5. Delete cost center (if no dependencies)
6. Verify removal from active list
```

### Test Case 2: Dependency Validation
```
1. Create cost center
2. Add cost center details (expenses, allocations)
3. Attempt to delete cost center
4. Verify deletion is blocked
5. Remove dependencies
6. Retry deletion successfully
```

### Test Case 3: Bulk Operations
```
1. Select multiple cost centers
2. Perform bulk delete operation
3. Verify success/failure messages
4. Test bulk restore operation
5. Verify appropriate status changes
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `costcenter(condation)` - For active/deleted filtering
   - `costcenter(userid)` - For user-based queries
   - `costcenterdetail(costcenterid)` - For dependency checks

2. **Query Optimization**:
   - Use COUNT() for dependency checks instead of loading all records
   - Index on condation field for show queries
   - Efficient bulk operations

3. **Memory Management**:
   - Process bulk operations in batches for large datasets
   - Clean up variables in loops
   - Optimize template assignments

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [costcenterReportController.md](costcenterReportController.md) - Cost center reporting
- [expensesController.php](#) - Expense management
- [Database Schema Documentation](#) - Table relationships

---

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