<?php

use \Symfony\Component\Yaml\Yaml;

$extension_id = 'cbext.clientbase.iptel_uiscom';

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

$settings = sql_fetch_assoc(
    sql_select($config['table_prefix'] .'settings', "name='$extension_id'")
)['value'] ?? '';
$settings = Yaml::parse($settings ?? "") ?? [];

if (empty($settings)) return;

$is_created = false;
foreach ($settings['table_fields'] as $field) {
    if ($field['field_name'] == 'ФИО сотрудника') {
        $is_created = true;
    }
}

if ($is_created) return;

$spec = [
    'fields' => [
        [
            "field_name" => "ФИО сотрудника",
            "type" => 3,
            "type_field" => 3,
            "sql_type_value" => '',
            "access" => [
                [
                    "group_id"  => 1,
                    "view_tb"   => 1,
                    "view_sub"  => 1,
                    "view_add"  => 0,
                    "view_edit" => 0,
                    "view"      => 1,
                    "read_acc"  => 1,
                    "write_acc" => 1,
                ]
            ],
        ],
    ]
];

$apiloc = new \CB\ApiLoc\ApilocGateway();
$apiloc->addFields($settings['conversation_records_table'], $spec);
$apiloc->addFieldAccesses($spec['fields'][0]);

$settings['table_fields'][] = [
    'id' => $spec['fields'][0]['id'],
    'field_name' => 'ФИО сотрудника'
];

sql_update($config['table_prefix'] .'settings', [
    'value' => Yaml::dump($settings, 8, 2)
], "name='$extension_id'");
