<?php
//добавим поле в котором будет храниться время в формате (ч:м:с)
$res = run_query("SHOW COLUMNS FROM " . $config['table_prefix'] . "module_asterisk_servers LIKE 'record_field_Length_other'");
if (!sql_num_rows($res)) {
    run_query("ALTER TABLE " . $config['table_prefix'] . "module_asterisk_servers ADD record_field_Length_other INT NOT NULL AFTER record_field_Length");
}

//если уже есть таблица разговоры, нужно создать новое поле и сязать его с таблицей
$sqlQuery = "SELECT record_field_Length_other,record_table,record_field_Length FROM " . $config['table_prefix'] . "module_asterisk_servers WHERE id=1";
$res = run_query($sqlQuery);
$row = sql_fetch_array($res);
if ($row['record_table'] && !$row['record_field_Length_other']) {
    // Длительность в формате (ч:м:с)
    $type_field = 3;
    $table_id = $row['record_table'];
    $field_name = 'record_field_Length_other';
    $ins_arr = array(
        'table_id' => $table_id,
        'field_num' => 13,
        'name_field' => 'Длительность в формате (ч:м:с)',
        'type_field' => $type_field,
        'default_value' => '00:00:00',
        'owner_id' => 1
    );
    $field_id = create_field_asterisk($table_id, $ins_arr, $type_field, 0, $field_name);

    //по всем записям нужно заполнить новое поле
    $sql = "SELECT " . 'f' . $row['record_field_Length'] . ", id FROM " . $config['table_prefix'] . "data" . $table_id . " WHERE status =0";
    $result = run_query($sql);
    while ($data_row = sql_fetch_array($result)) {
        $old_time = $data_row['f' . $row['record_field_Length']];
        $new_time = prepare_second_format($old_time);

        if ($new_time) {
            run_query("UPDATE " . $config["table_prefix"] . "data" . $table_id . " SET f" . $field_id . " = '" . $new_time . "' WHERE id=" . $data_row['id']);
        }
    }
}


function create_field_asterisk($table_id, $ins_arr, $type_field, $prev_id, $field_name)
{
    global $config;

    $field_id = sql_insert($config["table_prefix"] . "fields", $ins_arr); //exit;

    // Подсчитываем текущее количество полей у таблицы
    $res = sql_select_field($config["table_prefix"] . "fields", 'count(id) as count', 'table_id=', $table_id);
    $row5 = sql_fetch_array($res);
    $cur_fields_count = $row5["count"];

    // Собственно создание поля (для данных)
    $field_type = sql_type($type_field, $ins_arr["type_value"], $ins_arr["mult_value"]);
    if (($type_field == 3) && ($cur_fields_count > 30)) { // при очень большом количестве полей, заменяем на text
        $field_type = sql_type($type_field, 0, 1);
    }

    $sqlQuery = "ALTER TABLE " . $config["table_prefix"] . "data" . $table_id . " ADD f" . $field_id . " " . $field_type . " NOT NULL";
    $new_f_res = run_query($sqlQuery);

    $view_tb = 1;
    $view_edit = 0;

    // права доступа
    $defaultAdminAccess = array(
        'table_id' => $table_id,
        'field_id' => $field_id,
        'view_tb' => $view_tb,
        'view_add' => 0,
        'view_edit' => $view_edit,
        'view' => 1,
        'read_acc' => 1,
        'write_acc' => 1
    );
    $defaultAdminAccess['group_id'] = 1;
    sql_insert($config["table_prefix"] . "acc_fields", $defaultAdminAccess);

    $sqlQuery = "SELECT * FROM " . $config['table_prefix'] . "module_asterisk_servers WHERE id=1";
    $res = run_query($sqlQuery);
    if (sql_num_rows($res)) {
        run_query("UPDATE " . $config["table_prefix"] . "module_asterisk_servers SET " . $field_name . " = " . $field_id . " WHERE id=1");
    }

    return $field_id;
}


function prepare_second_format($time)
{

    $hour = floor($time / 3600);
    if ($hour) {
        if (strlen($hour) == 1) {
            $hour = "0" . $hour;
        }

        $time = $time - 3600 * $hour;
        $result_str = "$hour:";
        $minutes = floor($time / 60);
        if (strlen($minutes) == 1) {
            $minutes = "0" . $minutes;
        }

        $second = $time % 60;
        if (strlen($second) == 1) {
            $second = "0" . $second;
        }
        $result_str .= "$minutes:" . $second;

    } else {
        $result_str = "00:";
        $minutes = floor($time / 60);
        if (strlen($minutes) == 1) {
            $minutes = "0" . $minutes;
        } else {
            $minutes = "00:";
        }

        $second = $time % 60;
        if (strlen($second) == 1) {
            $second = "0" . $second;
        }

        $result_str .= "$minutes:" . $second;
    }
    return $result_str;
}
