<?php

global $g_comp_database;

$daoTenant = new \isys_cmdb_dao($g_comp_database);

$g_migration_log[] = '<span class="bold">Check for non-unique usernames...</span>';

$sql = "SELECT isys_cats_person_list__title AS title, COUNT(isys_cats_person_list__title) AS cnt
    FROM isys_cats_person_list
    WHERE isys_cats_person_list__title != '' AND isys_cats_person_list__title IS NOT NULL
    GROUP BY isys_cats_person_list__title
    HAVING COUNT(isys_cats_person_list__title) > 1;";

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

if (count($result) > 0) {
    $g_migration_log[] = '<span>Found some duplicated usernames:</span>';

    while ($row = $result->get_row()) {
        $amount = (int)$row['cnt'];

        $g_migration_log[] = '<span>Found ' . $amount . 'x "<strong>' . $row['title'] . '</strong>"</span>';

        $username = $daoTenant->convert_sql_text($row['title']);
        $sql = "SELECT isys_obj__id AS id, isys_obj__title AS title
            FROM isys_cats_person_list
            INNER JOIN isys_obj ON isys_obj__id = isys_cats_person_list__isys_obj__id
            WHERE isys_cats_person_list__title = {$username};";

        $duplicatesResult = $daoTenant->retrieve($sql);

        while ($duplicateRow = $duplicatesResult->get_row()) {
            $g_migration_log[] = '<span class="indent">In object <span class="text-monospace">#' . $duplicateRow['id'] . '</span>, object "' . $duplicateRow['title'] . '"</span>';
        }
    }

    $g_migration_log[] = '<span class="bold text-red">Please update the mentioned users!</span>';
    $g_migration_log[] = '<span class="bold">You can also check this list in the system overview of your administration area.</span>';
} else {
    $g_migration_log[] = '<span class="bold text-green">No action required!</span>';
}
