<?php

global $g_comp_database;

// Set migrationId
$migrationIdentifier = 'migrate_color_values';

if (!function_exists('unifyHexColor')) {
    // Move 'unifyHexColor' here in case the 'isys_helper_color' class is not available (might happen in CLI context).
    function unifyHexColor(string $color): string
    {
        // Remove anything not 0-9 or a-f, fill up with 'ffffff' and only use the first 6 characters.
        return '#' . substr(preg_replace('~[^0-9a-f]~', '', strtolower($color)) . 'ffffff', 0, 6);
    }
}

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

    $dao = new \isys_cmdb_dao($g_comp_database);

    // Objec types.
    $result = $dao->retrieve('SELECT isys_obj_type__id AS id, isys_obj_type__color AS color FROM isys_obj_type;');
    $g_migration_log[] = '<span>Migrate color values for all ' . count($result) . ' object types!</span>';

    while ($row = $result->get_row()) {
        $id = $dao->convert_sql_id($row['id']);
        $newColor = $dao->convert_sql_text(unifyHexColor((string)$row['color']));

        $dao->update("UPDATE isys_obj_type SET isys_obj_type__color = {$newColor} WHERE isys_obj_type__id = {$id} LIMIT 1;");
        $dao->apply_update();
    }

    // CMDB status.
    $result = $dao->retrieve('SELECT isys_cmdb_status__id AS id, isys_cmdb_status__color AS color FROM isys_cmdb_status;');
    $g_migration_log[] = '<span>Migrate color values for all ' . count($result) . ' CMDB status!</span>';

    while ($row = $result->get_row()) {
        $id = $dao->convert_sql_id($row['id']);
        $newColor = $dao->convert_sql_text(unifyHexColor((string)$row['color']));

        $dao->update("UPDATE isys_cmdb_status SET isys_cmdb_status__color = {$newColor} WHERE isys_cmdb_status__id = {$id} LIMIT 1;");
        $dao->apply_update();
    }

    // Net zone options.
    $result = $dao->retrieve('SELECT isys_catg_net_zone_options_list__id AS id, isys_catg_net_zone_options_list__color AS color FROM isys_catg_net_zone_options_list;');
    $g_migration_log[] = '<span>Migrate color values for all ' . count($result) . ' net zone options!</span>';

    while ($row = $result->get_row()) {
        $id = $dao->convert_sql_id($row['id']);
        $newColor = $dao->convert_sql_text(unifyHexColor((string)$row['color']));

        $dao->update("UPDATE isys_catg_net_zone_options_list SET isys_catg_net_zone_options_list__color = {$newColor} WHERE isys_catg_net_zone_options_list__id = {$id} LIMIT 1;");
        $dao->apply_update();
    }

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

    $this->migration_done($migrationIdentifier);
}
