<?php

/**
 * i-doit - Updates
 *
 * @package     i-doit
 * @subpackage  Update
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

/**
 * @var $g_comp_database isys_component_database
 */
global $g_comp_database;

// Set migration identifier.
$identifier = "overview_category_migration";

// Check if the migration has been executed before.
if ($this->is_migration_done($identifier)) {
    $g_migration_log[] = '<span class="bold">Migration of categories on object overview has already been done.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting Migration of categories on object overview.</span>';

    $dao = isys_cmdb_dao::instance($g_comp_database);

    // Get all object types that contain a specific category.
    $result = $dao->retrieve("SELECT isys_obj_type__const AS constant FROM isys_obj_type WHERE isys_obj_type__isysgui_cats__id <> '';");

    if (isset($tenantId) && is_numeric($tenantId)) {
        while ($row = $result->get_row()) {
            $key = 'cmdb.objtype.' . $row['constant'] . '.specific-cat-position';

            $dao = isys_cmdb_dao::instance($g_comp_database_system);

            $sql = "SELECT isys_settings__value AS val
            FROM isys_settings 
            WHERE isys_settings__key LIKE '{$key}'
            AND isys_settings__isys_mandator__id = {$tenantId};";

            $value = $dao->retrieve($sql)->get_row_value('val');

            // If no value is set, set the default value to 999.
            if ($value === null) {
                $sql = "INSERT INTO isys_settings
                    SET isys_settings__value = 999,
                    isys_settings__key = '{$key}',
                    isys_settings__isys_mandator__id = {$tenantId};";

                $dao->update($sql);
                $dao->apply_update();
            }
        }

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

        // Mark migration as done.
        $this->migration_done($identifier);
    } else {
        $g_migration_log[] = '<span class="bold">Please note that your specific categories might not be at the bottom of your overview pages any more!</span>';
    }
}
