<?php

global $g_comp_database, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = 'migrate_monetary_settings';

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

    $daoTenant = new \isys_cmdb_dao($g_comp_database);
    $daoSystem = new \isys_cmdb_dao($g_comp_database_system);

    $userLocaleIds = [];
    $tenantDatabaseName = $daoTenant->convert_sql_text($g_comp_database->get_db_name());
    $tenantId = (int)$daoSystem
        ->retrieve("SELECT isys_mandator__id AS id FROM isys_mandator WHERE isys_mandator__db_name = {$tenantDatabaseName} LIMIT 1;")
        ->get_row_value('id');

    $query = "SELECT isys_settings__value AS val
        FROM isys_settings
        WHERE isys_settings__key LIKE 'gui.currency'
        AND isys_settings__isys_mandator__id IN ({$tenantId}, 0)
        ORDER BY isys_settings__isys_mandator__id DESC
        LIMIT 1;";

    $defaultCurrencyId = (int)$daoSystem->retrieve($query)->get_row_value('val');
    $g_migration_log[] = '<span>Check "gui.currency" tenant setting value to use as default currency: ' . $defaultCurrencyId . '</span>';

    if ($defaultCurrencyId === 0) {
        $query = 'SELECT isys_currency__id AS id
            FROM isys_currency
            ORDER BY isys_currency__id ASC
            LIMIT 1;';

        $defaultCurrencyId = (int)$daoTenant->retrieve($query)->get_row_value('id');
        $g_migration_log[] = '<span class="indent">The "gui.currency" setting is empty, use first currency value to use as default: ' . $defaultCurrencyId . '</span>';
    }

    $query = 'SELECT isys_user_locale__id
        FROM isys_user_locale
        LEFT JOIN isys_currency ON isys_currency__id = isys_user_locale__isys_currency__id
        WHERE isys_currency__id IS NULL;';

    $result = $daoTenant->retrieve($query);

    while ($row = $result->get_row()) {
        $userLocaleIds[] = (int)$row['isys_user_locale__id'];
    }

    if (count($userLocaleIds)) {
        $userLocaleList = implode(', ', $userLocaleIds);
        $updateQuery = "UPDATE isys_user_locale
            SET isys_user_locale__isys_currency__id = {$defaultCurrencyId}
            WHERE isys_user_locale__id IN ({$userLocaleList});";

        $g_migration_log[] = '<span>Migrated ' . count($userLocaleIds) . ' entries!</span>';
        $daoTenant->update($updateQuery) && $daoTenant->apply_update();
    }


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

    $this->migration_done($migrationIdentifier);
}
