<?php

global $g_comp_database, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = 'migrate_user_e-mail-addresses';

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

    $daoTenant = new \isys_cmdb_dao($g_comp_database);

    try {
        // @see ID-11314 Read all primary e-mail addresses of 'person' objects.
        $readQuery = "SELECT isys_obj__id AS objectId,
            isys_obj__title AS objectTitle,
            isys_cats_person_list__id AS personEntryId,
            isys_catg_mail_addresses_list__title AS emailAddress
            FROM isys_cats_person_list
            INNER JOIN isys_obj ON isys_obj__id = isys_cats_person_list__isys_obj__id
            INNER JOIN isys_catg_mail_addresses_list ON isys_catg_mail_addresses_list__isys_obj__id = isys_obj__id
            WHERE isys_catg_mail_addresses_list__primary = 1
            AND isys_catg_mail_addresses_list__status = 2
            AND isys_catg_mail_addresses_list__title IS NOT NULL
            AND isys_catg_mail_addresses_list__title != ''
            GROUP BY isys_obj__id;";

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

        while ($row = $result->get_row()) {
            $entryId = (int)$row['personEntryId'];
            $row['emailAddress'] = trim($row['emailAddress']);

            // Verify that e-mail addresses are valid.
            if (filter_var($row['emailAddress'], FILTER_VALIDATE_EMAIL) === false) {
                $g_migration_log[] = '<span class="indent text-red">The primary e-mail address for user "' . $row['objectTitle'] . '" (#' . $row['objectId'] .
                    ') seems invalid and will be skipped!</span>';

                continue;
            }

            $g_migration_log[] = '<span class="indent">Use primary e-mail address as recovery e-mail address for "' . $row['objectTitle'] . '" (#' . $row['objectId'] .
                ')...</span>';
            $email = $daoTenant->convert_sql_text($row['emailAddress']);

            $updateQuery = "UPDATE isys_cats_person_list
                SET isys_cats_person_list__password_reset_email = {$email}
                WHERE isys_cats_person_list__id = {$entryId}
                LIMIT 1;";

            // Save e-mail addresses!
            $daoTenant->update($updateQuery);
            $daoTenant->apply_update($updateQuery);
        }
    } catch (Throwable $e) {
        $g_migration_log[] = '<span class="bold text-red">An error occured during the migration: ' . $e->getMessage() . '!</span>';
    }

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

    $this->migration_done($migrationIdentifier);
}
