public static function recalculateAllValueCustomers($livewire): void
{
$statePath = 'data';
$products = data_get($livewire, $statePath . '.products') ?? [];
// Retrieve parent fields from the state
$oceanFreight = (float) data_get($livewire, $statePath . '.ocean_freight', 0);
$tpFactor = (float) data_get($livewire, $statePath . '.value_customer_percentage', 0);
// Count only non-empty products (a product is non-empty if its "value" is not empty)
$nonEmptyProducts = collect($products)
->filter(fn($item) => isset($item['value']) && $item['value'] !== '')
->all();
$totalProducts = count($nonEmptyProducts) ?: 1;
// Update each product's "value_customer" in place
foreach ($products as $key => $product) {
if (empty($product['value'])) {
continue;
}
$unitaryPrice = (float) $product['value'];
$valueCustomer = ($oceanFreight / $totalProducts) + ($unitaryPrice * $tpFactor);
$formattedValue = number_format($valueCustomer, 2, '.', '');
// Only update if changed to avoid unnecessary refreshes
if (!isset($product['value_customer']) || $product['value_customer'] !== $formattedValue) {
$products[$key]['value_customer'] = $formattedValue;
}
}
// Update the Livewire state in place without re-indexing.
data_set($livewire, $statePath . '.products', $products);
}