<?php

// @see ID-10479 change root category with correct category as child of folder category -->

global $g_comp_database;

// Set migrationId
$migrationIdentifier = 'migrate-correct-specific-folder-categories';

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Correct root category with correct category already done.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Correct  root category with correct category...</span>';

    if (isys_application::isPro()) {
        $dao = new \isys_cmdb_dao($g_comp_database);

        $checks = [
            [
                'check' => "SELECT * FROM isys_category WHERE isys_category__isysgui_catg__id =
                    (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__CLUSTER_ROOT');",
                'update' => "UPDATE isys_category SET isys_category__isysgui_catg__id = (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__CLUSTER')
                    WHERE isys_category__isysgui_catg__id =
                    (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__CLUSTER_ROOT')",
            ],
            [
                'check' => "SELECT * FROM isys_category WHERE isys_category__isysgui_catg__id =
                    (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__VIRTUAL_HOST_ROOT');",
                'update' => "UPDATE isys_category SET isys_category__isysgui_catg__id = (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__VIRTUAL_HOST')
                    WHERE isys_category__isysgui_catg__id =
                    (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__VIRTUAL_HOST_ROOT')",
            ],
            [
                'check' => "SELECT * FROM isys_category WHERE isys_category__isysgui_catg__id =
                    (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__VIRTUAL_MACHINE__ROOT');",
                'update' => "UPDATE isys_category SET isys_category__isysgui_catg__id = (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__VIRTUAL_MACHINE')
                    WHERE isys_category__isysgui_catg__id =
                    (SELECT isysgui_catg__id FROM isysgui_catg  WHERE isysgui_catg__const = 'C__CATG__VIRTUAL_MACHINE__ROOT')",
            ]
        ];

        foreach ($checks as $check) {
            $resultCheck = $dao->retrieve($check['check']);
            if ($resultCheck->count() > 0) {
                $dao->update($check['update']);
            }
        }
        $dao->apply_update();
    }

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

    $this->migration_done($migrationIdentifier);
}
