<?php

// @see ID-10471 move JDisc unique ids from identifier to JDisc device information

global $g_comp_database;

// Set migrationId
$migrationIdentifier = 'migrate-jdsic-unique-ids';

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">JDisc unique IDs have already been moved</span>';
} else {
    $g_migration_log[] = '<span class="bold">Migrate uinque id data.</span>';

    $dao = new \isys_cmdb_dao_category_g_jdisc_device_information($g_comp_database);

    $result = $dao->retrieve(
        <<<SQL
        SELECT DISTINCT
            isys_catg_identifier_list__isys_obj__id AS obj_id,
            isys_catg_identifier_list__value AS unique_id,
            isys_catg_jdisc_device_information_list__id AS jdisc_info_id
        FROM isys_catg_identifier_list
        LEFT JOIN isys_catg_jdisc_device_information_list AS jdi ON isys_catg_identifier_list__isys_obj__id = isys_catg_jdisc_device_information_list__isys_obj__id
        WHERE
            isys_catg_identifier_list__isys_catg_identifier_type__id = (
                SELECT isys_catg_identifier_type__id
                FROM isys_catg_identifier_type
                WHERE isys_catg_identifier_type__const = 'C__CATG__IDENTIFIER_TYPE__JDISC'
                LIMIT 1
            )
        SQL
    );
    while ($row = $result->get_row()) {
        if ($row['jdisc_info_id']) {
            $dao->save_data(
                $row['jdisc_info_id'],
                [
                    'uniqueId' => $row['unique_id'],
                ]
            );
        } else {
            $dao->create_data(
                [
                    'isys_obj__id' => $row['obj_id'],
                    'uniqueId'     => $row['unique_id'],
                ]
            );
        }
    }

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

    $this->migration_done($migrationIdentifier);
}
