<?php

/**
 * i-doit - Updates
 *
 * Migrating validation so that every entry works on a class name basis.
 *
 * @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 migrationId
$g_migration_identifier = 'validation_via_classnames_migration';

// Check whether migration was executed before
if ($this->is_migration_done($g_migration_identifier)) {
    $g_migration_log[] = '<span class="bold">Validation configuration has already been migrated.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting validation configuration migration to work on a class name basis.</span>';

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

    // ---------- GLOBAL AND SPECIFIC CATEGORIES ----------

    $globalCategorySql = 'SELECT isys_validation_config__id AS id, isysgui_catg__class_name AS className
        FROM isys_validation_config 
        INNER JOIN isysgui_catg ON isysgui_catg__id = isys_validation_config__isysgui_catg__id
        WHERE isys_validation_config__isysgui_catg__id > 0';

    $specificCategorySql = 'SELECT isys_validation_config__id AS id, isysgui_cats__class_name AS className
        FROM isys_validation_config 
        INNER JOIN isysgui_cats ON isysgui_cats__id = isys_validation_config__isysgui_cats__id
        WHERE isys_validation_config__isysgui_cats__id > 0';

    $result = $dao->retrieve($globalCategorySql . ' UNION ' . $specificCategorySql . ';');

    $g_migration_log[] = '<span>Updating ' . count($result) . ' categories...</span>';

    while ($row = $result->get_row()) {
        $validationConfigurationId = $dao->convert_sql_id($row['id']);
        $className = $dao->convert_sql_text($row['className']);

        $updateSql = "UPDATE isys_validation_config 
            SET isys_validation_config__category_class = {$className} 
            WHERE isys_validation_config__id = {$validationConfigurationId} 
            LIMIT 1;";

        $dao->update($updateSql);
    }

    // ---------- REMAINING CUSTOM CATEGORIES ----------

    $g_migration_log[] = '<span>Updating remaining custom categories...</span>';
    $updateSql = 'UPDATE isys_validation_config 
        SET isys_validation_config__category_class = \'isys_cmdb_dao_category_g_custom_fields\' 
        WHERE isys_validation_config__isysgui_catg_custom__id > 0;';
    $dao->update($updateSql);

    $dao->apply_update();

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

    // Mark migration as done.
    $this->migration_done($g_migration_identifier);
}
