<?php

global $config;

$settingsKey = 'cbext.clientbase.gpt_proxy';

$tablesMeta = $config['table_prefix'] . 'tables';
$fieldsMeta = $config['table_prefix'] . 'fields';

$tableFullName = 'OpenAI Interaction Logger';
$fieldTitle    = 'Количество использованных токенов из OpenAI';

// 1) table_id
$res = run_query("
    SELECT id
    FROM `{$tablesMeta}`
    WHERE full_name = '" . addslashes($tableFullName) . "'
    LIMIT 1
");
$tableId = (int)($res['result']->fetch_assoc()['id'] ?? 0);
if ($tableId <= 0) return;

$dataTable = $config['table_prefix'] . 'data' . $tableId; // f_data510

// 2) поле уже есть?
$res = run_query("
    SELECT id
    FROM `{$fieldsMeta}`
    WHERE table_id = {$tableId}
      AND name_field = '" . addslashes($fieldTitle) . "'
    LIMIT 1
");
$fieldId = (int)($res['result']->fetch_assoc()['id'] ?? 0);

// 3) если нет — вставляем минимально
if ($fieldId <= 0) {
    $rNum = run_query("
        SELECT COALESCE(MAX(field_num),0) AS mx
        FROM `{$fieldsMeta}`
        WHERE table_id = {$tableId}
    ");
    $nextNum = (int)($rNum['result']->fetch_assoc()['mx'] ?? 0) + 1;

    run_query("
        INSERT INTO `{$fieldsMeta}` 
            (table_id, field_num, name_field, type_field, created_by)
        VALUES 
            ({$tableId}, {$nextNum}, '" . addslashes($fieldTitle) . "', 1, 'gpt_proxy_openai_token')
    ");

    $res = run_query("SELECT LAST_INSERT_ID() AS id");
    $fieldId = (int)($res['result']->fetch_assoc()['id'] ?? 0);
}

// 4) гарантируем колонку в f_dataXXX
$columnName = 'f' . $fieldId;

$colRes = run_query("SHOW COLUMNS FROM `{$dataTable}` LIKE '" . addslashes($columnName) . "'");
$hasCol = (int)($colRes['result']->num_rows ?? 0);

if ($hasCol === 0) {
    run_query("ALTER TABLE `{$dataTable}` ADD COLUMN `{$columnName}` BIGINT NOT NULL DEFAULT 0");
}

// 5) settings: logger_table.openai_token = fieldId
$sm = \CB\core()->SETTINGS_MANAGER;
$settings = $sm->get($settingsKey);

if (empty($settings['logger_table']) || !is_array($settings['logger_table'])) {
    $settings['logger_table'] = [];
}
$settings['logger_table']['id'] = $tableId;
$settings['logger_table']['openai_token'] = $fieldId;

$sm->set($settingsKey, $settings);