<?php

/**
 * @var $g_comp_database isys_component_database
 */
global $g_comp_database, $g_absdir, $g_mandator_info, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = "auth-own-object-right";

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Migration of right "Created objects by user itself" has already been done.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting Migration of right "Created objects by user itself".</span>';

    $sumRights = array_sum([
        isys_auth::VIEW,
        isys_auth::EDIT,
        isys_auth::DELETE,
        isys_auth::ARCHIVE,
        isys_auth::SUPERVISOR
    ]);

    $insert = "INSERT INTO isys_auth
            (isys_auth__isys_obj__id, isys_auth__type, isys_auth__isys_module__id, isys_auth__path, isys_auth__status)
            VALUES %s";

    $dao = \isys_cmdb_dao::instance($g_comp_database);

    $status = $dao->convert_sql_int(defined_or_default('C__RECORD_STATUS__NORMAL', 2));
    $module = defined_or_default('C__MODULE__CMDB');

    if ($module === null) {
        $module = $dao->retrieve('SELECT isys_module__id FROM isys_module
            WHERE isys_module__const = ' . $dao->convert_sql_text('C__MODULE__CMDB') . ' LIMIT 1:')
            ->get_row_value('isys_module__id');
    }

    $valuePattern = "(
            %s,
            " . $dao->convert_sql_int($sumRights) . ",
            " . $dao->convert_sql_id($module) . ",
            'OBJ_OWNER',
            " . $status . "
        )";

    $values = [];
    $migrationDone = true;

    // Get all Persons who are in status Normal
    $query = "SELECT isys_cats_person_list__isys_obj__id as objectId FROM isys_cats_person_list
            WHERE isys_cats_person_list__status = " . $status;
    $result = $dao->retrieve($query);
    while($row = $result->get_row()) {
        $values[] = sprintf($valuePattern, $row['objectId']);
    }

    if (!empty($values)) {
        $dao->set_autocommit(false);
        $dao->begin_update();
        $insert = sprintf($insert, implode(',', $values));
        if (!($dao->update($insert) && $dao->apply_update())) {
            $dao->cancel_update();
            $g_migration_log[] = '<span class="bold red">Migrating the right "Created objects by user itself" failed! Please check the logs.</span>';
            $migrationDone = false;
        } else {
            $g_migration_log[] = '<span class="bold">Migration finished!</span>';
        }
    }

    if ($migrationDone) {
        $this->migration_done($migrationIdentifier);
    }
}
