<?php

$extension_id = 'cbext.clientbase.wazzup';

/** @var \CB\Platform\ExtensionManager */
$extension_manager = \CB\Core::get(\CB\Core::EXTENSION_MANAGER);
if (!$extension_manager->isActive($extension_id)) {
    return;
}

/** @var \CB\Service\SettingsManager */
$settings_manager = \CB\Core::get(\CB\Core::SETTINGS_MANAGER);
$settings = $settings_manager->get($extension_id);

if (empty($settings)) {
    return;
}

$chat_type = [
    'tgapi'     => 'Telegram',
    'whatsapp'  => 'Whatsapp',
    'instagram' => 'Instagram',
    ''          => 'Чат',
];

foreach (($settings['channels'] ?? []) as $channel) {
    $chat = $chat_type[($channel['transport'] ?? '')] .':';

    foreach (($channel['additional_option'] ?? []) as $option) {
        $table_name = sql_fetch_assoc(sql_select_field(
            "{$config['table_prefix']}tables",
            'name_table as table_name',
            'id='. (int)($option['table_id'] ?? 0)
        ))['table_name'] ?? 'table_name';

        $field_name = sql_fetch_assoc(sql_select_field(
            "{$config['table_prefix']}fields",
            'name_field as field_name',
            'id='. (int)($option['phone_field_id'] ?? 0)
        ))['field_name'] ?? 'field_name';


        //"<Соц.сеть>:' '<Название таблицы>/<Название поля>"
        sql_update("{$config['table_prefix']}fields", [
            'name_field' => "$chat $table_name/$field_name"
        ], 'id='. (int)($option['link_field_id'] ?? 0));
    }
}
