<?php

global $g_comp_database, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = 'migrate_user_settings';

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">User settings have already been migrated</span>';
} else {
    $g_migration_log[] = '<span class="bold">Migrate the user settings...</span>';

    $daoTenant = new \isys_cmdb_dao($g_comp_database);
    $daoSystem = new \isys_cmdb_dao($g_comp_database_system);

    $tenantDatabaseName = $daoTenant->convert_sql_text($g_comp_database->get_db_name());
    $tenantId = (int)$daoSystem
        ->retrieve("SELECT isys_mandator__id AS id FROM isys_mandator WHERE isys_mandator__db_name = {$tenantDatabaseName} LIMIT 1;")
        ->get_row_value('id');

    $sql = 'SELECT isys_user_locale__default_tree_view AS defaultTreeView,
        isys_user_locale__default_tree_type AS defaultTreeType,
        isys_user_setting__isys_obj__id AS userObjectId
        FROM isys_user_locale
        INNER JOIN isys_user_setting ON isys_user_setting__id = isys_user_locale__isys_user_setting__id;';

    $counter = 0;
    $result = $daoTenant->retrieve($sql);

    while ($row = $result->get_row()) {
        $userObjectId = $daoTenant->convert_sql_id($row['userObjectId']);
        $defaultTreeType = $daoTenant->convert_sql_int($row['defaultTreeType'] ?: C__CMDB__VIEW__TREE_LOCATION__LOCATION);
        $defaultTreeView = $daoTenant->convert_sql_int($row['defaultTreeView'] ?: C__CMDB__VIEW__TREE_OBJECTTYPE);

        // Create a user setting for default tree type.
        $updateSql = "REPLACE INTO isys_settings
            SET isys_settings__key = 'gui.default-tree-type',
                isys_settings__value = {$defaultTreeType},
                isys_settings__isys_obj__id = {$userObjectId};";

        try {
            $daoTenant->update($updateSql);
            $daoTenant->apply_update();
        } catch (Throwable $e) {
            // Do nothing to prevent 'duplicate entry' errors.
        }

        // Create a user setting for default tree view.
        $updateSql = "REPLACE INTO isys_settings
            SET isys_settings__key = 'gui.default-tree-view',
                isys_settings__value = {$defaultTreeView},
                isys_settings__isys_obj__id = {$userObjectId};";

        try {
            $daoTenant->update($updateSql);
            $daoTenant->apply_update();
        } catch (Throwable $e) {
            // Do nothing to prevent 'duplicate entry' errors.
        }

        $counter ++;
    }

    $g_migration_log[] = '<span>Migrated ' . $counter . ' user settings regarding default tree views / types!</span>';

    $sql = 'SELECT isys_user_ui__tree_visible AS treeVisibility,
        isys_user_setting__isys_obj__id AS userObjectId
        FROM isys_user_ui
        INNER JOIN isys_user_setting ON isys_user_setting__id = isys_user_ui__isys_user_setting__id;';

    $counter = 0;
    $result = $daoTenant->retrieve($sql);

    while ($row = $result->get_row()) {
        $userObjectId = $daoTenant->convert_sql_id($row['userObjectId']);
        $hideEmptyObjectTypes = $row['treeVisibility'] % 2 === 0 ? 0 : 1;
        $hideEmptyCategories = $row['treeVisibility'] % 1 === 0 ? 0 : 1;

        // Create a user setting for default tree view.
        $updateSql = "REPLACE INTO isys_settings
            SET isys_settings__key = 'gui.tree.hide-empty-object-types',
                isys_settings__value = {$hideEmptyObjectTypes},
                isys_settings__isys_obj__id = {$userObjectId};";

        try {
            $daoTenant->update($updateSql);
            $daoTenant->apply_update();
        } catch (Throwable $e) {
            // Do nothing to prevent 'duplicate entry' errors.
        }

        // Create a user setting for default tree view.
        $updateSql = "REPLACE INTO isys_settings
            SET isys_settings__key = 'gui.tree.hide-empty-categories',
                isys_settings__value = {$hideEmptyCategories},
                isys_settings__isys_obj__id = {$userObjectId};";

        try {
            $daoTenant->update($updateSql);
            $daoTenant->apply_update();
        } catch (Throwable $e) {
            // Do nothing to prevent 'duplicate entry' errors.
        }

        $counter ++;
    }

    $g_migration_log[] = '<span>Migrated ' . $counter . ' user settings regarding tree visibility!</span>';

    // Migrate the 'IP-Handling' setting
    $sql = "SELECT isys_setting__value AS value
        FROM isys_setting
        INNER JOIN isys_setting_key ON isys_setting_key__id = isys_setting__isys_setting_key__id
        WHERE isys_setting_key__const = 'C__MANDATORY_SETTING__IP_HANDLING';";

    $ipHandlingValue = $daoTenant->convert_sql_int($daoTenant->retrieve($sql)->get_row_value('value'));

    $updateSql = "REPLACE INTO isys_settings
        SET isys_settings__key = 'cmdb.release-ip-on-archive-delete',
            isys_settings__value = {$ipHandlingValue},
            isys_settings__isys_mandator__id = {$tenantId};";

    try {
        $daoSystem->update($updateSql);
        $daoSystem->apply_update();
    } catch (Throwable $e) {
        // Do nothing to prevent 'duplicate entry' errors.
    }

    $g_migration_log[] = '<span>Migrated the "IP-Handling" setting!</span>';

    // @see ID-9442 Migrate the API system settings to tenant settings.
    $query = "SELECT *
        FROM isys_settings
        WHERE isys_settings__isys_mandator__id  = 0
        AND isys_settings__key IN ('api.authenticated-users-only', 'api.log-level', 'api.status', 'api.strip-tags', 'api.validation');";

    $result = $daoSystem->retrieve($query);

    while ($row = $result->get_row()) {
        $key = $row['isys_settings__key'];
        $value = (int)$row['isys_settings__value'];

        $updateSql = "REPLACE INTO isys_settings
            SET isys_settings__key = '{$key}',
                isys_settings__value = {$value},
                isys_settings__isys_mandator__id = {$tenantId};";

        try {
            $daoSystem->update($updateSql);
            $daoSystem->apply_update();
        } catch (Throwable $e) {
            // Do nothing.
        }
    }

    $g_migration_log[] = '<span>Migrated available "API" system settings to be tenant settings!</span>';

    $g_migration_log[] = '<span class="bold">Migration finished!</span>';

    $this->migration_done($migrationIdentifier);
}
