{*
  Шаблон вычисления "Сумма по подтаблице"
*}

$filter = sql_select_array(FILTERS_TABLE, 'id = ', get_filter_id({$filter|default:0}));
if ($line['{$gen_field.link_field_id}']['raw']) {
    $arr_id = explode('-', trim($line['{$gen_field.link_field_id}']['raw'], '-'));
    foreach ($arr_id as $par_id) {
        $result = data_select_field(
            $table_id,
            'sum({$cur_field}) as f_sum',
            'status = ', $line['{$gen_field.link_field_id}']['status'], ' AND ({$gen_field.link_field_id} = ', $par_id, ' OR {$gen_field.link_field_id} LIKE "%-' . $par_id . '-%")' .
            ($event['type'] === 'delete' ? ' AND id != ' . $ID : '') .
            ($filter['value'] ? ' AND (' . filter_tpl_replace($filter['value']) . ')' : '')
        );
        $row = sql_fetch_assoc($result);
        data_update({$gen_field.table}, EVENTS_ENABLE, ['{$gen_field.field}' => ($row['f_sum'] ?? 0)], 'id = ', $par_id);
    }
}

if ($event['changed'][{$gen_field.link_field_id|substr:1}]['old']) {
    $arr_id = explode('-', trim($event['changed'][{$gen_field.link_field_id|substr:1}]['old'], '-'));
    foreach ($arr_id as $par_id) {
        $result = data_select_field(
            $table_id,
            'sum({$cur_field}) as f_sum',
            'status = ', $line['{$gen_field.link_field_id}']['status'], ' AND ({$gen_field.link_field_id} = ', $par_id, ' OR {$gen_field.link_field_id} LIKE "%-' . $par_id . '-%")' .
            ($filter['value'] ? ' AND (' . filter_tpl_replace($filter['value']) . ')' : '')
        );
        $row = sql_fetch_assoc($result);
        data_update({$gen_field.table}, EVENTS_ENABLE, ['{$gen_field.field}' => ($row['f_sum'] ?? 0)], 'id = ', $par_id);
    }
}