<?php

/**
 * i-doit - Updates
 *
 * Migrating "create report" rights to a new state.
 *
 * @package     i-doit
 * @subpackage  Update
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

/** @var $g_comp_database isys_component_database */
global $g_comp_database;

// Set migrationId
$g_migration_identifier = 'create_report_right_migration';

// Check whether migration was executed before
if ($this->is_migration_done($g_migration_identifier)) {
    $g_migration_log[] = '<span class="bold">Reports rights have already been migrated.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting migration of "create report" rights.</span>';

    $migrated = 0;
    $dao = isys_cmdb_dao::instance($g_comp_database);

    $reportModuleId = $dao
        ->retrieve('SELECT isys_module__id AS id FROM isys_module WHERE isys_module__const = \'C__MODULE__REPORT\' LIMIT 1')
        ->get_row_value('id');

    $reportModuleId = $dao->convert_sql_id($reportModuleId);
    $executeRight = $dao->convert_sql_int(isys_auth::EXECUTE);
    $createRight = $dao->convert_sql_int(isys_auth::CREATE);
    $statusNormal = $dao->convert_sql_int(C__RECORD_STATUS__NORMAL);

    $pathsToCreate = ['REPORTS_IN_CATEGORY/*', 'REPORTS_IN_CATEGORY'];

    $sql = "SELECT DISTINCT isys_auth__isys_obj__id AS objectId
        FROM isys_auth
        WHERE isys_auth__path LIKE 'EDITOR'
        AND isys_auth__type = {$executeRight}
        AND isys_auth__isys_module__id = {$reportModuleId};";

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

    // For each (unique) user we create the necessary two new rights:
    while ($row = $result->get_row()) {
        $migrated ++;
        $userObjectId = $dao->convert_sql_id($row['objectId']);

        foreach ($pathsToCreate as $path) {
            $sql = "INSERT INTO isys_auth SET
                isys_auth__isys_obj__id = {$userObjectId},
                isys_auth__type = {$createRight},
                isys_auth__isys_module__id = {$reportModuleId},
                isys_auth__path = '{$path}',
                isys_auth__status = {$statusNormal};";

            $dao->update($sql) && $dao->apply_update();
        }
    }

    $g_migration_log[] = '<span>Migrated the rights for ' . $migrated . ' user!</span>';

    $sql = "SELECT COUNT(1) AS cnt
        FROM isys_auth
        WHERE isys_auth__path LIKE 'EDITOR'
        AND isys_auth__isys_module__id = {$reportModuleId};";

    $removed = (int) $dao->retrieve($sql)->get_row_value('cnt');

    $sql = "DELETE FROM isys_auth
        WHERE isys_auth__path LIKE 'EDITOR'
        AND isys_auth__isys_module__id = {$reportModuleId};";

    $dao->update($sql) && $dao->apply_update();

    $g_migration_log[] = '<span>Removed ' . $removed . ' old rights that are not necessary any more!</span>';
    $g_migration_log[] = '<span class="bold">Migration finished!</span>';

    // Mark migration as done
    $this->migration_done($g_migration_identifier);
}
