<?php

global $g_comp_database;

// Set migrationId
$migrationIdentifier = "reset_ports_foreign_key";

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Ports foreign key is already reset.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Start resetting ports foreign key.</span>';

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

    $fk = $this->get_foreign_key('isys_catg_port_list')['isys_catg_port_list__isys_plug_type__id'];

    if ($fk[C__SQL__REFERENCED_TABLE] == 'isys_connection_type' && !empty($fk[C__SQL__CONSTRAINT])) {
        $g_migration_log[] = '<span>Ports foreign key is already set correctly.</span>';
    } else {
        if (isset($fk[C__SQL__FOREIGN_KEY])) {
            $dao->update("ALTER TABLE isys_catg_port_list DROP FOREIGN KEY `" . $fk[C__SQL__FOREIGN_KEY] . "`;");
            $g_migration_log[] = '<span>Dropped previous foreign key `' . $fk[C__SQL__FOREIGN_KEY] . '`.</span>';
        }
        $update = "ALTER TABLE isys_catg_port_list
            ADD CONSTRAINT `isys_catg_port_list__isys_plug_type__id` FOREIGN KEY (`isys_catg_port_list__isys_plug_type__id`)
            REFERENCES `isys_connection_type` (`isys_connection_type__id`) ON DELETE SET NULL ON UPDATE CASCADE;";
        if ($dao->update($update) && $dao->apply_update()) {
            $g_migration_log[] = '<span>Successfully reset ports foreign key.</span>';
        } else {
            $g_migration_log[] = '<span class="bold red">Resetting the ports foreign key failed! Please check the logs.</span>';
        }
    }

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

    $this->migration_done($migrationIdentifier);
}
