<?php
global $all_modules;
//массив для заполнения столбца created_by
$created_by_fields = [
    "Идентификатор сообщения" => 'Wazzup_id_message',
    "Дата сообщения" => 'Wazzup_date_message',
    "Статус сообщения" => 'Wazzup_status_message',
    "Адресат" => 'Wazzup_address',
    "Сообщение" => 'Wazzup_message',
    "Файл" => 'Wazzup_file',
    "Название канала" => 'Wazzup_channel_name',
    "Тип чата" => 'Wazzup_chat_type',
    "Ответственный" => 'Wazzup_responsible',
    'Идентификатор чата' => 'Wazzup_id',
    'Никнейм' => 'Wazzup_nickname',
    'Телефон' => 'Wazzup_phone',
    'Тип чата' => 'Wazzup_chat_type',
];
//Добавляем колонку created_by в таблицах tables и fields
$tablePrefix = $config['table_prefix'];

// Проверяем, существует ли колонка created_by в таблице `tables`
$result = run_query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = '{$tablePrefix}tables' AND COLUMN_NAME = 'created_by'");

if (isset($result['result']) && $result['result']->num_rows == 0) {
    run_query("ALTER TABLE {$tablePrefix}tables ADD COLUMN created_by VARCHAR(255) DEFAULT NULL");
}

// Проверяем, существует ли колонка created_by в таблице `fields`
$result = run_query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = '{$tablePrefix}fields' AND COLUMN_NAME = 'created_by'");

if (isset($result['result']) && $result['result']->num_rows == 0) {
    run_query("ALTER TABLE {$tablePrefix}fields ADD COLUMN created_by VARCHAR(255) DEFAULT NULL");
}
if (!empty($all_modules['wazzup'])) {
    $extension_manager = \CB\Core::get(\CB\Core::EXTENSION_MANAGER);
    if (!$extension_manager->isActive('cbext.clientbase.wazzup')) {
        //Получаем настройки модуля
        $wazzupSettings = \CB\core()->SETTINGS_MANAGER->get('cbext.clientbase.wazzup');
        if(!empty($wazzupSettings)) {
            if(!empty($wazzupSettings['channels'])) {
                //Составляем запрос для обновления полей связи
                $queryInformation = [];
                //Создаем масив для изменения Наименования канала в таблице Wazzup_log
                $newChannelName =[];
                foreach ($wazzupSettings['channels'] as $chanel) {
                    foreach ($chanel['additional_option'] as $chanelTable) {
                        $queryInformation[$chanelTable['table_id']][0] .= "WHEN f".$chanelTable['link_field_id']." != 0 THEN f".$chanelTable['link_field_id']. PHP_EOL;
                        $newChannelName[$chanelTable['link_field_id']] = $chanel['channel_name']." (".$chanel['plain_id'].")";
                    } 
                }
            }
            if(!empty($wazzupSettings['table'])) {
                if(!empty($wazzupSettings['table']['id'])) {
                    $tableID = $wazzupSettings['table']['id'];
                    //Обнавляем таблицу Wazzup_log присваиваем created_by
                    run_query("UPDATE {$tablePrefix}tables SET created_by = 'Wazzup_log' WHERE id = $tableID");

                    $updateCases = [];
                    $values = [];
                    $fieldIds = [];
                    foreach ($wazzupSettings['table']['fields'] as $field) {
                        $updateCases[] = "WHEN id = {$field['field_id']} THEN '{$created_by_fields[$field['field_name']]}'";
                        $fieldIds[] = $field['field_id'];
                    }
                    // Обновляем поля таблицы Wazzup_log присваиваем created_by
                    if (!empty($updateCases)) {
                        $casesSql = implode(' ', $updateCases);
                        $fieldIdsSql = implode(',', $fieldIds);
                        run_query("UPDATE {$tablePrefix}fields SET created_by = CASE $casesSql END WHERE id IN ($fieldIdsSql)");
                    }
                    // Добавляем поля в таблицу protect для защиты от редактирования
                    $channelNameFieldId = $wazzupSettings['table']['fields']['channel_name']['field_id'];
                    run_query("UPDATE {$tablePrefix}fields SET type_field = 4 WHERE id = $channelNameFieldId"); // Название канала делаем списком
                }
            }
            if (!empty($wazzupSettings['reference_table'])) {
                if (!empty($wazzupSettings['reference_table']['id'])) {
                    // Обновляем таблицу, присваиваем created_by
                    $tableId = $wazzupSettings['reference_table']['id'];
                    run_query("UPDATE {$tablePrefix}tables SET created_by = 'Wazzup_guide' WHERE id = $tableId");
                
                    // Обновляем поля, используя один запрос
                    $updateCases = [];
                    $fieldIds = [];
                
                    foreach ($wazzupSettings['reference_table']['fields'] as $field) {
                        $updateCases[] = "WHEN id = {$field['field_id']} THEN '{$created_by_fields[$field['field_name']]}'";
                        $fieldIds[] = $field['field_id'];
                    }
                
                    if (!empty($updateCases)) {
                        $casesSql = implode(' ', $updateCases);
                        $fieldIdsSql = implode(',', $fieldIds);
                        run_query("UPDATE {$tablePrefix}fields SET created_by = CASE $casesSql END WHERE id IN ($fieldIdsSql)");
                    }
                }
            }
            if(!empty($wazzupSettings['channels'])) {
                //Обнавляем настройки модуля
                $save = \CB\Core::get(\CB\Core::EXTENSION_MANAGER)->getService('cbext.clientbase.wazzup', 'SaveHandler');
                //формирование тела запроса на сохранение настройки
                $body = [
                    'api_key' => $wazzupSettings['api_key'],
                    'webhook_uri' => $wazzupSettings['webhook_uri'],
                    'groups' => $wazzupSettings['groups'],
                    'users' => $wazzupSettings['users'],
                    'channels' => $wazzupSettings['channels'],
                    'def_chan_for_reminder' => array_key_first($wazzupSettings['channels']),
                    'maximum_number_of_messages_per_hour' => $wazzupSettings['maximum_number_of_messages_per_hour'],
                ];
                $headers['Content-Type'] = 'application/json';
                //формирование запроса
                $request = new  \GuzzleHttp\Psr7\ServerRequest(
                    'POST',
                    '/save',
                    $headers,
                    json_encode($body)
                );
                //отправка запроса
                $save->handle($request);
                //Получаем новые настройки после обновления
                $newWazzupSettings = \CB\core()->SETTINGS_MANAGER->get('cbext.clientbase.wazzup');
                
                //обновляем Названия каналов в таблице Wazzup_log
                $updateChannelName = [];
                foreach ($newChannelName as $column => $volume) {
                    $updateChannelName[] = "WHEN f{$column} IS NOT NULL AND f{$column} != '' THEN '$volume'";
                }

                $queryUpdateChannelName = "UPDATE `" . DATA_TABLE . $newWazzupSettings['table']['id'] . "` 
                SET f{$channelNameFieldId} = CASE 
                    " . implode(' ', $updateChannelName) . "
                    ELSE f{$channelNameFieldId} 
                END";

                run_query($queryUpdateChannelName);

                //Обновляем поля связи
                foreach ($newWazzupSettings['channels'] as $chanel) {
                    foreach ($chanel['additional_option'] as $chanelTable) {
                        if(!$queryInformation[$chanelTable['table_id']][1]) {
                            $queryInformation[$chanelTable['table_id']][1] = $chanelTable['link_field_id'];
                        }
                    }
                }
                if (!empty($queryInformation)) {
                    foreach($queryInformation as $value) {
                        //формируем окончательный запрос
                        $query = "UPDATE `".DATA_TABLE.$newWazzupSettings['table']['id']."` SET f".$value[1]." = CASE ".$value[0]. "ELSE f".$value[1]." END;";
                        run_query($query);
                    }
                }

                $subtables = sql_select_field(
                    SUBTABLES_TABLE,
                    'id',
                    'name LIKE "%(Wazzup)%"'
                );
                // удаляем старые подтаблицы
                while($subtable_id = sql_fetch_assoc($subtables)) {
                    sql_query("DELETE FROM {$tablePrefix}subtables WHERE id=". $subtable_id['id']);
                    sql_query("DELETE FROM {$tablePrefix}acc_subtables WHERE subtable_id=".$subtable_id['id']);
                    sql_query("DELETE FROM {$tablePrefix}acc_subtable_rules WHERE subtable_id=".$subtable_id['id']);
                }
            }
        }
    }
}