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

$start_time = time();
$files = $line['{$imp_file_field}'] ? explode("\r\n", $line['{$imp_file_field}']) : [];
foreach ($files as $fname) {
    $fpath = get_file_path({$imp_file_field|replace:'f':''}, $ID, $fname);
{if $imp_template}
    import_data({$subtable.table}, '{$imp_template}', $fpath, 'none');
{else}
    $imp_fields = get_table_fields(get_table({$subtable.table}));
    // читаем заголовок
    $beg_str = 1;
    $fd = fopen($fpath, 'r');
    while (($str = fgets($fd)) !== false) {
        $beg_str++;
        if (($str = trim($str)) !== '') break;
    }
    fclose($fd);
    // подбираем кодировку и разделитель
    $charsets = $GLOBALS['charsets'];
    $separators = [",", ";", "|", "\t", " "];
    $max_match_cols = 0;
    foreach ($charsets as $ch_cur => $ch_name) {
        $test_str = iconv($ch_cur, 'utf-8', $str);
        foreach ($separators as $sep_cur) {
            $headers = str_getcsv($test_str, $sep_cur);
            $match_cols = 0;
            foreach ($imp_fields as $one_field) {
                if (in_array($one_field['name_field'], $headers)) {
                    $match_cols++;
                }
            }
            if ($match_cols > $max_match_cols) {
                $max_match_cols = $match_cols;
                $charset = $ch_cur;
                $separator = $sep_cur;
            }
        }
    }
    // формируем шаблон импорта
    $import_data = [
        'is_excel' => 0,
        'charset' => $charset,
        'separator' => $separator,
        'beg_str' => $beg_str,
        'unic_field_handler' => 1,
        'unic_empty_priority' => 1,
        'links_process' => 2,
        'run_calculations_import' => 1
    ];
    $headers = str_getcsv(iconv($charset, 'utf-8', $str), $separator);
    foreach ($headers as $i => $header_name) {
        foreach ($imp_fields as $one_field) {
            if ($header_name == $one_field['name_field']) {
                $import_data['col'.$one_field['id']] = $i + 1;
            }
        }
    }
    import_data({$subtable.table}, $import_data, $fpath, 'none');
{/if}
}
data_update({$subtable.table}, EVENTS_ENABLE, [
    '{$subtable.link_field_id}' => $ID
], "add_time >= '", date('Y-m-d H:i:s', $start_time), "' AND {$subtable.link_field_id} = 0");