# Capital Controller Documentation

**File**: `/controllers/capitalController.php`  
**Purpose**: Manage company capital accounts and integrate with chart of accounts system  
**Last Updated**: December 20, 2024  
**Total Functions**: 3  
**Lines of Code**: ~159

---

## 📋 Overview

The Capital Controller manages company capital accounts and their integration with the chart of accounts system. It handles:
- Capital amount management and editing
- Integration with the accounts tree (chart of accounts)
- Capital account creation and updates
- Tree element management for capital entries
- Print-friendly capital reports
- YouTube tutorial integration for user guidance

### Primary Functions
- [x] Edit and update capital amounts
- [x] Create capital records with account tree integration
- [x] Generate capital reports
- [x] Manage account tree relationships
- [x] Print-friendly capital statements
- [x] Handle both new capital creation and existing capital updates

### Related Controllers
- [accountstree.php](accountstree.md) - Account tree management
- [dailyentry.php](dailyentry.md) - Journal entry operations
- [balancereportController.php](balancereportController.md) - Financial reporting

---

## 🗄️ Database Tables

### Primary Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **capital** | Capital accounts | capitalid, capitalamount, treeId |
| **accountstree** | Chart of accounts | id, customName, parent, theValue, itemtype, itemtype2 |

### Support Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default/Edit Action** - Capital Display and Editing
**Location**: Line 65  
**Purpose**: Display capital editing interface with current values

**Function Signature**:
```php
// Triggered when: do=edit or empty $do
```

**Process Flow**:
1. Include authentication check
2. Load YouTube tutorial links
3. Call edit() function to get capital data
4. Assign data to template
5. Display edit form via capitalview/edit.html

**Template Variables**:
- `capitalData` - Current capital information
- `youtubes` - Tutorial video links
- `customValidation` - Enable form validation

---

### 2. **edit()** - Capital Data Retrieval
**Location**: Line 104  
**Purpose**: Load current capital data or create default structure

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

**Process Flow**:
1. Set capital ID to 1 (system default)
2. Attempt to load existing capital record
3. If no record exists, create default object
4. Return capital data object

**Default Capital Structure**:
```php
if (!isset($capitalData)) {
    $capitalData = new stdClass();
    $capitalData->capitalamount = 0;
    $capitalData->capitalid = 0;
}
```

**Return Value**: Capital object with amount and ID information

---

### 3. **update()** - Capital Management with Account Tree Integration
**Location**: Line 117  
**Purpose**: Create or update capital records with full account tree integration

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

**Process Flow**:
1. Extract POST data (capitalid, capitalamount)
2. Determine if this is insert or update operation
3. Handle account tree integration
4. Create or update capital record
5. Manage tree element relationships

**Insert Operation (capitalid == 0)**:
```php
if ($capitalid == 0) { // Insert
    $capital->capitalamount = $capitalamount;
    $capital->treeId = 50; // Default tree position
    $capitalDAO->insert($capital);

    if ($capital->treeId > 0) {
        $capitalTreeId = $capital->treeId;
        $accountsTree = $accountsTreeDAO->load($capitalTreeId);
        $accountsTree->theValue = $capitalamount;
        editTreeElement($accountsTree); // Update tree value
    } else {
        // Create new tree element if needed
        $treeId = addTreeElement("رأس المال", 120, 1, 0, 1, '', 0, $capitalamount);
        $capitalDAO->update($capital);
    }
}
```

**Update Operation (capitalid != 0)**:
```php
else { // Update
    $oldData = $capitalDAO->load($capitalid);
    
    $capital->capitalamount = $capitalamount;
    $capital->treeId = $oldData->treeId;
    $capital->capitalid = 1; // Force ID to 1

    if ($capital->treeId > 0) {
        $capitalTreeId = $capital->treeId;
        $accountsTree = $accountsTreeDAO->load($capitalTreeId);
        $accountsTree->theValue = $capitalamount;
        editTreeElement($accountsTree); // Update tree value
    } else {
        // Create tree element if missing
        $treeId = addTreeElement("رأس المال", 120, 1, 0, 1, '', 0, $capitalamount);
    }
    $capitalDAO->update($capital);
}
```

**Tree Element Parameters**:
- Name: "رأس المال" (Capital in Arabic)
- Parent: 120 (Equity section)
- Level: 1
- Type: 0
- Item Type: 1
- Value: Capital amount

---

### 4. **editprint Action** - Print-Friendly Display
**Location**: Line 73  
**Purpose**: Generate print-optimized capital report

**Process Flow**:
1. Include authentication check
2. Load capital data via edit() function
3. Assign data to template
4. Display via capitalview/editprint.html
5. Set customPrint flag for print styling

---

## 🔄 Workflows

### Workflow 1: Capital Amount Update
```
┌─────────────────────────────────────────────────────────────┐
│                START: Access Capital Management            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Current Capital Data                              │
│     - Check if capital record exists (ID = 1)             │
│     - Load existing amount or set default to 0            │
│     - Display in edit form                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Updates Capital Amount                            │
│     - Enter new capital amount                             │
│     - Submit form via POST                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Determine Operation Type                               │
│     IF capitalid == 0:                                     │
│       └─→ New capital creation                            │
│     ELSE:                                                  │
│       └─→ Update existing capital                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Handle Account Tree Integration                        │
│     IF treeId exists:                                      │
│       │                                                    │
│       ├─→ Load existing tree element                      │
│       ├─→ Update theValue with new amount                 │
│       └─→ Call editTreeElement()                          │
│     ELSE:                                                  │
│       └─→ Create new tree element "رأس المال"            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Save Capital Record                                    │
│     - Update capital table with new amount                │
│     - Ensure capitalid is set to 1                        │
│     - Maintain treeId relationship                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Display Success                                        │
│     - Redirect to success page                            │
│     - Capital amount updated in both tables               │
│     - Account tree reflects new capital value             │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Account Tree Integration Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Capital Tree Integration               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Check Existing Tree Relationship                      │
│     IF capital.treeId > 0:                                │
│       └─→ Tree element exists                            │
│     ELSE:                                                  │
│       └─→ Need to create tree element                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2A. Update Existing Tree Element                         │
│     - Load accountstree record by treeId                  │
│     - Update theValue field with capital amount           │
│     - Call editTreeElement() to persist changes           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2B. Create New Tree Element (if needed)                  │
│     Parameters:                                            │
│     - customName: "رأس المال" (Capital)                  │
│     - parent: 120 (Equity section)                        │
│     - level: 1                                            │
│     - type: 0                                             │
│     - itemtype: 1                                         │
│     - value: capital amount                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Maintain Data Consistency                              │
│     - Capital table shows current amount                  │
│     - Account tree shows same amount in theValue          │
│     - Both tables reference each other via treeId         │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=edit` | `edit()` + display form | Show capital editing interface |
| `do=editprint` | `edit()` + print view | Generate print-friendly capital report |
| `do=update` | `update()` | Update capital amount and account tree |
| `do=sucess` | Show template | Display success message |
| `do=error` | Show template | Display error message |

### Required Parameters by Action

**Capital Update** (`do=update`):
- `capitalid` - Current capital ID (0 for new, existing ID for update)
- `capitalamount` - New capital amount

---

## 🧮 Data Integration Features

### Account Tree Integration
The capital controller demonstrates sophisticated integration between business entities and the chart of accounts:

```php
// Capital record structure
$capital->capitalamount = $capitalamount;  // Business amount
$capital->treeId = 50;                     // Link to accounts tree

// Account tree structure  
$accountsTree->theValue = $capitalamount;  // Same amount in tree
$accountsTree->customName = "رأس المال";   // Arabic name
$accountsTree->parent = 120;               // Under equity section
```

### Tree Element Functions
The controller uses external functions from `dailyentryfun.php`:
- `addTreeElement()` - Create new account tree nodes
- `editTreeElement()` - Update existing tree values

### Data Consistency
Both tables maintain the same capital amount:
- `capital.capitalamount` - Business entity value
- `accountstree.theValue` - Chart of accounts value

---

## 📊 Business Logic Features

### Single Capital Management
- System enforces single capital record (ID = 1)
- Updates always target the same record
- Prevents multiple capital accounts

### Default Values
- New capital starts at amount 0
- Default tree position under equity (parent 120)
- Automatic tree creation if missing

### Arabic Language Support
- Capital account named "رأس المال"
- Arabic success/error messages
- RTL-compatible templates

---

## 🔒 Security & Validation

### Access Control
```php
include_once("../public/authentication.php");
```
- All operations require authentication
- Session-based user validation

### Input Validation
- Capital ID validated for insert/update logic
- Amount validation handled by template forms
- Tree ID validation for account relationships

### Error Handling
```php
try {
    update();
    header("location:?do=sucess");
} catch (Exception $e) {
    header("location:?do=error");
}
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Tree Integration**
**Issue**: Capital amount not reflected in account tree  
**Cause**: Tree ID relationship broken

**Fix**:
```sql
-- Check capital to tree relationship
SELECT c.capitalamount, a.theValue, c.treeId 
FROM capital c 
LEFT JOIN accountstree a ON a.id = c.treeId;

-- Update tree value manually if needed
UPDATE accountstree 
SET theValue = (SELECT capitalamount FROM capital WHERE capitalid = 1)
WHERE id = (SELECT treeId FROM capital WHERE capitalid = 1);
```

### 2. **Multiple Capital Records**
**Issue**: System creates multiple capital records  
**Cause**: Logic not enforcing single record

**Solution**: Always use capitalid = 1 for updates

### 3. **Tree Element Creation Failures**
**Issue**: New tree elements not created  
**Cause**: Missing dailyentryfun.php functions

**Fix**: Ensure `addTreeElement()` and `editTreeElement()` functions are available

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [accountstree.md](accountstree.md) - Account tree management
- [dailyentry.md](dailyentry.md) - Journal entry operations

---

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