<?php

$result = sql_select_array($config["table_prefix"] . 'calc_template', 'id = 116');
if ($result['id']) {
	return;
}

$sql_query = 'INSERT INTO `' . $config["table_prefix"] . 'calc_template`';
$sql_query .= <<<'EOT'
(`id`, `name`, `calculate_tpl`, `params`, `type`, `tpl_name`, `javascript_tpl`, `tpl_category`, `calc_types`, `calc_num`) VALUES
(116, 'Автонумерация в подтаблице', "$receiver_field = get_field('{$receiver_field}');
$rel_table = '{$display_none|default:-1}';
$result = sql_select_field(SUBTABLES_TABLE, 'link_field_id', 'table_id = ' . $rel_table . ' AND link_table_id = ' . $receiver_field['table_id']);
$row = sql_fetch_assoc($result);
$current_record = data_select_array($receiver_field['table_id'], 'id = ' . $line['id']);
if ($current_record['f' . $row['link_field_id']] > 0) {
    $result = sql_fetch_assoc(data_select_field($receiver_field['table_id'], 'MAX(f' . $receiver_field['id'] . ') as max',
        'status=0 AND f' . $row['link_field_id'] . ' = ' . $current_record['f' . $row['link_field_id']]));
    $line['f' . $receiver_field['id']] = $result['max'] + 1;
}", '{
    "title": "Автонумерация в подтаблице",
    "help": "autonumbering_in_a_subtable",
    "parameters": {
        "receiver_field": {
            "type": "Field",
            "name": "receiver_field",
            "description": "Поле-получатель",
            "help": "receiver_field",
            "type_field": 1
        },
        "display_none": {
            "type": "String",
            "name": "display_none",
            "description": "display_none",
            "help": ""
        }
    },
    "events": [
        {
            "type": 1,
            "field": ""
        }
    ]
}', 'calc', 'autonumbering_in_a_subtable.tpl', '', '2', '[2]', '6');
EOT;
run_query($sql_query);
