<?php

global $g_comp_database, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = 'migrate_jdisc_profile_matching';

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">JDisc Profile Matching have already been migrated</span>';
} else {
    $g_migration_log[] = '<span class="bold">Migrate the JDisc Profile Matchings...</span>';

    $dao = new \isys_jdisc_dao($g_comp_database);

    $sql = '
        SELECT
            isys_jdisc_profile__id,
            isys_jdisc_profile__isys_obj_match__id
        FROM isys_jdisc_profile
    ';
    $result  = $dao->retrieve($sql);
    $isError = false;
    while ($row = $result->get_row()) {
        $profileID  = (int) $row['isys_jdisc_profile__id'];
        $objMatchID = (int) $row['isys_jdisc_profile__isys_obj_match__id'];

        // Set matchID for each object assignment
        if ($objMatchID) {
            $updateSql = "
                UPDATE isys_jdisc_object_type_assignment
                SET isys_jdisc_object_type_assignment__isys_obj_match__id = {$objMatchID}
                WHERE isys_jdisc_object_type_assignment__isys_jdisc_profile__id = {$profileID}
            ";
            try {
                $dao->update($updateSql);
                $dao->apply_update();
            } catch (Throwable $e) {
                $isError = true;
                $errMsg  = $e->getMessage();
                $g_migration_log[] = "
                    <span class='bold'>Error setting matchId {$objMatchID} for profile {$profileID}:</span>
                    <span>{$errMsg}</span>
                ";
            }
        }
    }

    // drop column if no errors
    if (!$isError) {
        $sql = '
            ALTER TABLE isys_jdisc_profile
            DROP FOREIGN KEY isys_jdisc_profile__isys_obj_match__id,
            DROP COLUMN isys_jdisc_profile__isys_obj_match__id;
        ';
        $dao->update($sql);
        $dao->apply_update();
    }

    $g_migration_log[] = '<span>Migrated available JDisc profile Matchings!</span>';
    $g_migration_log[] = '<span class="bold">Migration finished!</span>';

    $this->migration_done($migrationIdentifier);
}
