<?php

/**
 * i-doit - Updates
 *
 * Migrating relation types so that every entry contains a constant.
 *
 * @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 = 'relation_type_constants_migration';

if (!function_exists('generateConstant')) {
    /**
     * Will create a (custom) relation type constant.
     *
     * @param string        $title
     * @param isys_cmdb_dao $dao
     *
     * @return string
     * @throws isys_exception_database
     */
    function generateConstant(string $title, isys_cmdb_dao $dao): string
    {
        $constant = strtoupper($title);
        $constant = preg_replace('~(\s|-)+~', '_', $constant);
        $constant = preg_replace('~_{2,}~', '_', $constant);
        $constant = preg_replace('~[^a-z0-9_]~i', '', $constant);

        $counter = 1;
        $finalConstant = 'C__RELATION_TYPE_CUSTOM__' . $constant;

        // Find a valid constant, that has not yet been taken.
        while (!isConstantAvailable($finalConstant, $dao)) {
            $finalConstant = 'C__RELATION_TYPE_CUSTOM__' . $constant . '_' . $counter;
            $counter++;

            if ($counter > 10) {
                break;
            }
        }

        return $finalConstant;
    }
}

if (!function_exists('isConstantAvailable')) {
    /**
     * @param string        $constant
     * @param isys_cmdb_dao $dao
     *
     * @return bool
     * @throws isys_exception_database
     */
    function isConstantAvailable(string $constant, isys_cmdb_dao $dao): bool
    {
        $sql = 'SELECT isys_relation_type__id 
            FROM isys_relation_type 
            WHERE isys_relation_type__const = ' . $dao->convert_sql_text($constant) . '
            LIMIT 1;';

        return $dao->retrieve($sql)->get_row_value('isys_relation_type__id') === null;
    }
}

// Check whether migration was executed before
if ($this->is_migration_done($g_migration_identifier)) {
    $g_migration_log[] = '<span class="bold">Relation types have already been migrated.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting relation type migration to add constants to custom relation types.</span>';

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

    $sql = "SELECT isys_relation_type__id AS id, isys_relation_type__title AS title 
        FROM isys_relation_type 
        WHERE isys_relation_type__const = '' 
        OR isys_relation_type__const IS NULL;";

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

    while ($row = $result->get_row()){
        $constant = generateConstant($row['title'], $dao);

        $g_migration_log[] = '<span class="indent">Add constant "' . $constant . '" for relation type #' . $row['id'] . '!</span>';

        $updateSql = 'UPDATE isys_relation_type 
            SET isys_relation_type__const = ' . $dao->convert_sql_text($constant) . '
            WHERE isys_relation_type__id = ' . $row['id'] . '
            LIMIT 1;';

        $dao->update($updateSql);

        $dao->apply_update();
    }

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

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