<?php
global $config, $sql_global_link, $sql_db_type, $channel_tables;

if ($link_identifier == 0) {
    $link_identifier = $sql_global_link;
}
if ($sql_db_type == "mysql") {
    $db_name = "table_schema";
}
if ($sql_db_type == "postgresql") {
    $db_name = "table_catalog";
}
$res = run_query('SHOW COLUMNS FROM ' . $config['table_prefix'] . 'modules LIKE "block"');
if (sql_num_rows($res)) {
    $result = run_query('SELECT * FROM ' . $config['table_prefix'] . 'modules WHERE `name` = "asterisk" AND `block` = 1');
    if (sql_num_rows($result)) {
        $tables_res = run_query("SELECT * FROM information_schema.tables WHERE $db_name='" . $config['dbname'] . "' AND `table_name` LIKE '%module_asterisk_phone_table%'");
        while ($row = sql_fetch_assoc($tables_res)) {
            run_query('DELETE FROM ' . $row['TABLE_NAME']);
        }
        $config_res = run_query('SELECT * FROM ' . $config['table_prefix'] . 'config WHERE `name` = "Phone_fix"');
        if ($row = sql_fetch_assoc($config_res)) {
            if ($decode_row = json_decode($row['value'], true)) {
                if (is_array($decode_row) && count($decode_row) > 0) {
                    $new_row = array();
                    foreach ($decode_row as $t_id=>$t_info) {
                        $new_row[$t_id] = array(
                            'field' => $t_info['field'],
                            'last_id' => 0,
                        );
                    }
                    $new_row = json_encode($new_row);
                    if ($sql_db_type == "mysql") {
                        $new_row = mysqli_escape_string($link_identifier, $new_row);
                    } elseif ($sql_db_type == "postgresql") {
                        $new_row = pg_escape_string($link_identifier, $new_row);
                    }
                    run_query('UPDATE ' . $config['table_prefix'] . 'config SET `value` = "' . $new_row .  '" WHERE `name` = "Phone_fix"');
                }
            }
        }
    }
}