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

{if !$table1 || !$table2}
return;
{/if}
{if {$f1|@json_encode} != "null"}
$arr['f1'] = json_decode('{$f1|@json_encode}', true);
{else}
return;
{/if}
{if {$f2|@json_encode} != "null"}
$arr['f2'] = json_decode('{$f2|@json_encode}', true);
{else}
return;
{/if}
{if {$f3|@json_encode} != "null"}
$arr['f3'] = json_decode('{$f3|@json_encode}', true);
{/if}
{if $filter}
$filter = sql_select_array(FILTERS_TABLE, 'id = ', get_filter_id({$filter|default:0}));
$filter = $filter['value'] ? ' AND (' . filter_tpl_replace($filter['value']) . ')' : '';
{/if}

$par_link_field_id = sql_fetch_row(sql_select_field(SUBTABLES_TABLE, 'link_field_id', 'table_id = ', $table_id, ' AND link_table_id = ', get_table_id({$table2|default:-1})))[0];
{if $link_field}
$link_table_id =  explode('|', sql_fetch_row(sql_select_field(FIELDS_TABLE, 'type_value', 'id = ', get_field_id({$link_field|substr:1})))[0])[0];
$link_field_id = sql_fetch_row(sql_select_field(FIELDS_TABLE, 'id', "table_id = ",  get_table_id({$table1}), " AND type_value LIKE '" . $link_table_id . "|%'"))[0];
$link_lines = explode('-', trim($line['{$link_field}']['raw'], '-'));
if ($event['changed'][{$link_field|substr:1}]) {
    $old_values = explode('-', trim($event['changed'][{$link_field|substr:1}]['old'], '-'));
    $link_lines = array_diff($link_lines, $old_values);
}
$link_filter = ' AND f'.$link_field_id.' IN (' . implode(',', $link_lines) . ')';
{/if}

$result = data_select({$table1|default:0}, 'status = 0'{if $filter} . $filter{/if}{if $link_field} . $link_filter{/if});
while($row = sql_fetch_assoc($result)) {
    $arr_insert = [];
    foreach($arr['f1'] as $key => $value) {
        if (isset($arr['f2'][$key])) {
            $arr_insert['f' . $arr['f2'][$key]] = !empty($arr['f3'][$key]) ? $arr['f3'][$key] : $row['f' . $value];
        }
    }

    if (!array_key_exists('f'.$par_link_field_id, $arr_insert)) {
        $arr_insert['f'.$par_link_field_id] = $line['id'];
    }
    data_insert({$table2|default:0}, EVENTS_ENABLE, $arr_insert);
}