# Corrected Legacy Increment Logic

## Issue

Legacy loans use `loans.legacy_paid` as the authoritative `total_repaid` value. The previous payment logic incorrectly subtracted new M-Pesa allocations from this field.

## Correct Behavior

Every successful payment allocated to a legacy loan must increase `legacy_paid`:

```php
$updatedLegacyPaid = round(
    (float) ($loan->legacy_paid ?? 0) + $paymentAmount,
    2
);

$loan->update(['legacy_paid' => $updatedLegacyPaid]);
```

Normal loans continue to calculate `total_repaid` from the sum of repayment `amount_paid` values.

## Payment Paths

Both paths use `RepaymentService::recordLoanPayment()`:

- CSV payment imports
- Non-STK C2B payments

Therefore, the shared service correction applies consistently to both payment sources.

## Reconciliation

Payments processed while the old subtraction logic was active were reconciled from `payment_allocations` using rows with a non-null M-Pesa transaction ID. Original legacy-import allocations were excluded.

For loan `9812`:

- Historical imported total: KSh 20,250.00
- Three M-Pesa payments: KSh 4,500.00
- Correct `total_repaid`: **KSh 24,750.00**

The reconciliation utility is:

```text
scripts/reconcile_legacy_paid_from_history.php
```

This is a one-time correction utility. Do not run `--apply` again with the same cutoff.
