<?php

global $g_comp_database, $g_comp_database_system, $g_crypto_hash;

// Set migrationId
$migrationIdentifier = 'migrate_system_crypto_hash_to_tenant';

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">System Crypto hash has already been migrated</span>';
} else {
    $g_migration_log[] = '<span class="bold">Migrate System Crypto hash</span>';

    $daoSystem = new \isys_cmdb_dao($g_comp_database_system);
    $result = $daoSystem->retrieve('SELECT isys_mandator__id as id FROM isys_mandator WHERE isys_mandator__crypto_hash IS NULL;');
    $counter = $result->count();

    if ($counter === 0) {
        $g_migration_log[] = '<span>There are no tenants with no crypto hash configured.</span>';
        $this->migration_done($migrationIdentifier);
        return;
    }
    $ids = [];
    while ($row = $result->get_row()) {
        $ids[] = (int) $row['id'];
    }

    $update = sprintf("UPDATE isys_mandator SET isys_mandator__crypto_hash = {$daoSystem->convert_sql_text($g_crypto_hash)}
                     WHERE isys_mandator__id IN (%s);", implode(',', $ids));

    try {
        $daoSystem->update($update);
        $daoSystem->apply_update();
    } catch (Throwable $e) {
        // Do nothing to prevent 'duplicate entry' errors.
    }
    $g_migration_log[] = '<span>Migrated ' . $counter . ' tenants!</span>';
    $g_migration_log[] = '<span class="bold">Migration finished!</span>';

    $this->migration_done($migrationIdentifier);
}
