# CECLCOMP.PHP Calculation Updates

## Overview
Updated `ceclcomp.php` with improved calculation logic from the legacy system to fix potential calculation errors in the Homogenous Pools and Total rows.

## Changes Made

### ✅ **1. Dynamic Balance and Reserve Tracking**
**Before:** Used the last row's `totalbalance` field from the database, which doesn't represent the sum of all pools.

**After:** Tracks balances and reserves as it loops through each pool:

```php
// Initialize accumulators before loop
$dynamic_total_balance = 0;  // For calculating homogenous pools balance
$dynamic_total_reserve = 0;  // For calculating total loss rate

// During loop - accumulate for each pool
$dynamic_total_balance += $row["CurrentBalance"];
$dynamic_total_reserve += $totalreservefinalraw;
```

### ✅ **2. Branch Table Field Handling**
**Added:** Better handling for missing fields when displaying branch-specific data:

```php
// Handle missing totalreserveconf fields in branch tables
if (isset($row["totalreserveconf"])) {
    $totalreserve = number_format($row["totalreserveconf"], 0);
} else {
    $totalreserve = number_format($row["totalconfreserve"], 0);
}

if (isset($row["totalreservepercconf"])) {
    $totalreserveperc = sprintf("%.2f%%", $row["totalreservepercconf"] * 100);
} else {
    $totalreserveperc = sprintf("%.2f%%", $row["totalconfreserveperc"] * 100);
}
```

### ✅ **3. Homogenous Pools Row - Accurate Calculations**
**Before:** Displayed the last row's total balance (incorrect).

**After:** Uses dynamically calculated totals:

```php
// Calculate dynamic homogenous pools values
$dynamic_homogenous_balance = number_format($dynamic_total_balance, 0);
$dynamic_homogenous_reserve = number_format($dynamic_total_reserve, 0);
$dynamic_homogenous_loss_rate = $dynamic_total_balance > 0 ? 
    sprintf("%.2f%%", ($dynamic_total_reserve / $dynamic_total_balance) * 100) : "0.00%";
```

### ✅ **4. Final Totals Calculation**
**Before:** Used potentially incorrect values from the database's summary fields.

**After:** Calculates totals from accumulated values:

```php
// Calculate final totals using dynamic values
// For branch mode, use zeros for specific allocations
$branch_specific_balance = ($branch != '') ? 0 : $totalspecbalance;
$branch_specific_reserve = ($branch != '') ? 0 : $totalspecific;

$finalreserveraw = $dynamic_total_reserve + $branch_specific_reserve;
$finalreserve = number_format($finalreserveraw, 0);

// Use dynamic calculations for final totals
$final_total_balance = $dynamic_total_balance + $branch_specific_balance;
$final_total_reserve = $dynamic_total_reserve + $branch_specific_reserve;
$finalperc = $final_total_balance > 0 ? 
    sprintf("%.2f%%", ($final_total_reserve / $final_total_balance) * 100) : "0.00%";
$finalbalance = number_format($final_total_balance, 0);
```

### ✅ **5. Branch Mode Handling**
**Added:** Proper handling to show zeros for specific allocations when viewing branch data:

```php
// For branch mode, show zeros for specific allocations
if ($branch != '') {
    $totalspecbalance_formatted = "0";
    $specificperc = "0.00%";
    $formatted_specific = "0";
} else {
    // Never try to format an already formatted string
    $formatted_specific = number_format($totalspecific, 0);
}
```

## What Was NOT Changed

### ✅ **Preserved:**
- ✅ Portal authentication (`portal-auth-simple.php`)
- ✅ JWT token handling for all navigation links
- ✅ Session management using portal variables
- ✅ Role-based access control
- ✅ Shortname handling for internal admins, examiners, and multi-bank users
- ✅ All UI elements and JavaScript functions
- ✅ Toggle codes/descriptions functionality
- ✅ Negative amortization warning system
- ✅ Pool grouping and subpool sorting logic
- ✅ Risk Rating handling
- ✅ Custom pool descriptions
- ✅ All navigation links with token preservation

## Impact

### **Bug Fixes:**
1. **Homogenous Pools Row** - Now displays accurate sum of all pool balances and reserves
2. **Total Loss Rate** - Now calculated correctly based on actual totals, not last row's data
3. **Final Total Row** - Accurately reflects sum of homogenous pools + specific allocations
4. **Branch View** - Correctly shows zeros for specific allocations in branch mode

### **Data Accuracy:**
- Banks with multiple loan pools will now see correct totals
- Banks using branch-level reporting will see proper field handling
- Reserve calculations are now mathematically accurate across all views

### **No Breaking Changes:**
- All existing functionality preserved
- No changes to authentication or permissions
- No changes to navigation or UI
- No changes to database queries (only calculation logic)

## Testing Recommendations

### **Test Cases:**
1. **Single Pool Bank:**
   - Verify totals match before and after (should be identical)

2. **Multiple Pool Bank:**
   - Verify Homogenous Pools row shows sum of all pools
   - Verify Total Loss Rate is calculated correctly
   - Verify Final Total row matches sum of homogenous + specific

3. **Bank with Specific Allocations:**
   - Verify specific allocations are added correctly to totals
   - Verify percentage calculations are accurate

4. **Branch View:**
   - Verify specific allocations show as $0 and 0.00%
   - Verify totals only include branch data

5. **Bank with Subpools (e.g., Risk Ratings):**
   - Verify all subpools are included in totals
   - Verify sorting order is preserved

## Files Modified

- `unified-portal/cecl-app/ceclcomp.php` - Calculation logic updates (lines 820-1000)

## Deployment Notes

- ✅ No database changes required
- ✅ No configuration changes required
- ✅ Backward compatible - no breaking changes
- ✅ No authentication or permission changes
- ✅ Safe to deploy immediately

## Technical Details

### **Why This Matters:**
The previous logic was using the `totalbalance` field from the **last row** in the database query results, which is a summary field that might not accurately represent the sum of all individual pool balances being displayed. By accumulating totals as we iterate through each pool, we ensure the displayed totals match the actual sum of the rows shown on the page.

### **Calculation Flow:**
1. Initialize dynamic accumulators to zero
2. Loop through each loan pool (main pools and subpools)
3. For each pool, accumulate its balance and calculated reserve
4. Display Homogenous Pools row using accumulated totals
5. Add specific allocations (from separate table)
6. Display Final Total row using accumulated + specific totals

### **Edge Cases Handled:**
- Division by zero (checks if balance > 0 before calculating percentages)
- Branch mode (uses 0 for specific allocations)
- Missing fields in branch tables (conditional field name checks)
- Formatted vs raw values (uses raw for calculations, formatted for display)

