<?php

/**
 * i-doit - Updates
 *
 * Migrating plug types
 *
 * @package     i-doit
 * @subpackage  Update
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @author      Kevin Mauel <kmauel@i-doit.com>
 */

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

// Set migrationId
$g_migration_identifier = "plug_type_migration";

// Check whether migration was executed before
if ($this->is_migration_done($g_migration_identifier)) {
    $g_migration_log[] = '<span class="bold">Migration of plug types has already been done.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting Migration of plug types.</span>';

    do {
        // Retrieve highest id of connection types
        $highestConnectionTypeId = $g_comp_database->retrieveArrayFromResource($g_comp_database->query('SELECT isys_connection_type__id FROM isys_connection_type WHERE TRUE ORDER BY isys_connection_type__id DESC LIMIT 1;'))[0]['isys_connection_type__id'];

        // Retrieve all plug types
        $plugTypes = $g_comp_database->retrieveArrayFromResource($g_comp_database->query('SELECT * FROM isys_plug_type WHERE TRUE'));

        // Remove foreign key checks for plug types

        // @see  ID-7170 Check if the foreign keys exist before dropping them.
        $parsedTableInfo = (new isys_update_migration())->get_foreign_key('isys_catg_port_list');

        foreach ($parsedTableInfo as $field => $info) {
            if ($info[C__SQL__FOREIGN_KEY] === 'isys_catg_port_list_ibfk_3') {
                $g_comp_database->query('ALTER TABLE `isys_catg_port_list` DROP FOREIGN KEY `isys_catg_port_list_ibfk_3`;') && $g_comp_database->commit();
            }

            if ($info[C__SQL__FOREIGN_KEY] === 'isys_catg_port_list_ibfk_5') {
                $g_comp_database->query('ALTER TABLE `isys_catg_port_list` DROP FOREIGN KEY `isys_catg_port_list_ibfk_5`;') && $g_comp_database->commit();
            }
        }

        foreach ($plugTypes as &$plugType) {
            // Recalculate id for connection type
            $plugType['isys_plug_type__id_new'] = $plugType['isys_plug_type__id'] + $highestConnectionTypeId;

            $g_comp_database->query("
              INSERT INTO isys_connection_type (isys_connection_type__id, isys_connection_type__sort, isys_connection_type__title, isys_connection_type__description, isys_connection_type__const, isys_connection_type__status)
              VALUES ({$plugType['isys_plug_type__id_new']}, {$plugType['isys_plug_type__id_new']}, '{$plugType['isys_plug_type__title']}', '{$plugType['isys_plug_type__description']}', '{$plugType['isys_plug_type__const']}', {$plugType['isys_plug_type__status']})
           ") && $g_comp_database->commit();

            // Change plug type ids to connector type ids
            $g_comp_database->query("UPDATE isys_catg_port_list SET isys_catg_port_list__isys_plug_type__id = {$plugType['isys_plug_type__id_new']} WHERE isys_catg_port_list__isys_plug_type__id = {$plugType['isys_plug_type__id']}") &&
            $g_comp_database->commit();
        }

        // Set new foreign key
        $g_comp_database->query('
              ALTER TABLE isys_catg_port_list
              ADD CONSTRAINT isys_catg_port_list_ibfk_14
              FOREIGN KEY (isys_catg_port_list__isys_plug_type__id)
              REFERENCES isys_connection_type(isys_connection_type__id);
           ') && $g_comp_database->commit();

        // Remove plug types table
        $g_comp_database->query('DROP TABLE isys_plug_type;') && $g_comp_database->commit();
    } while (false);

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

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