<?php

global $g_comp_database, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = 'migrate_uploaded_images';

// @phpstan-ignore-next-line
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Uploaded images have already been migrated</span>';
} else {
    $g_migration_log[] = '<span class="bold">Migrate uploaded images to new folders...</span>';

    $daoTenant = new \isys_cmdb_dao($g_comp_database);
    $daoSystem = new \isys_cmdb_dao($g_comp_database_system);

    $coreObjectTypeImages = json_decode(file_get_contents(__DIR__ . '/object-type-images.json'), true);
    $coreObjectTypeIcons = json_decode(file_get_contents(__DIR__ . '/object-type-icons.json'), true);

    $tenantDatabaseName = $daoTenant->convert_sql_text($g_comp_database->get_db_name());
    $tenantId = (int)$daoSystem
        ->retrieve("SELECT isys_mandator__id AS id FROM isys_mandator WHERE isys_mandator__db_name = {$tenantDatabaseName} LIMIT 1;")
        ->get_row_value('id');

    $idoitRootPath = str_replace('\\', '/', dirname(dirname(dirname(dirname(__DIR__))))) . '/';

    // At first we will migrate the object images and afterwards clear the empty directories.
    $g_migration_log[] = '<span class="bold">1. Move uploaded object images:</span>';
    $oldObjectImagesPath = "{$idoitRootPath}upload/images/{$tenantId}/";
    $newObjectImagesPath = "{$idoitRootPath}upload/images/{$tenantId}/object-images/";

    foreach(glob($oldObjectImagesPath . '*/*') as $oldObjectImagePath) {
        if (is_dir($oldObjectImagePath)) {
            continue;
        }

        // Get the filename.
        $imageFilename = basename($oldObjectImagePath);
        // Generate the sub-directory part.
        $subDirectory =  substr(md5($imageFilename), 0, 2);

        $newObjectImageDirectory = "{$newObjectImagesPath}{$subDirectory}";
        $newObjectImagePath = "{$newObjectImagesPath}{$subDirectory}/{$imageFilename}";

        if (!is_dir($newObjectImageDirectory) && !mkdir($newObjectImageDirectory, 0775, true)) {
            $g_migration_log[] = '<span class="indent text-red"><strong>Attention!</strong> The new image folder ' . $newObjectImageDirectory . ' could not be created, due to missing rights!</span>';
            continue;
        }

        if (rename($oldObjectImagePath, $newObjectImagePath)) {
            $g_migration_log[] = 'Moved <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $oldObjectImagePath) . '</span><br />To <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $newObjectImagePath) . '</span>';
        } else {
            $g_migration_log[] = '<span class="ident text-red"><strong>Attention!</strong> The object image <span class="text-monospace">' . str_replace($idoitRootPath, '', $oldObjectImagePath) . '</span> could not be moved to <span class="text-monospace">' . str_replace($idoitRootPath, '', $newObjectImagePath) . '</span>!</span>';
        }
    }

    // Here we will remove any empty directories.
    foreach(glob($oldObjectImagesPath . '*', GLOB_ONLYDIR) as $oldObjectImageDir) {
        if (basename($oldObjectImageDir) === 'object-images') {
            // Skip our newly created image path ;)
            continue;
        }

        if (count(glob("$oldObjectImageDir/*")) > 0) {
            $g_migration_log[] = '<span class="ident"><strong>Attention!</strong> The folder <span class="text-monospace">' . str_replace($idoitRootPath, '', $oldObjectImageDir) . '</span> still contains data and will not be deleted!</span>';
            continue;
        }

        if (rmdir($oldObjectImageDir)) {
            $g_migration_log[] = 'Deleted empty folder <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $oldObjectImageDir) . '</span></span>';
        } else {
            $g_migration_log[] = '<span class="ident text-red"><strong>Attention!</strong> The empty folder <span class="text-monospace">' . str_replace($idoitRootPath, '', $oldObjectImageDir) . '</span> could not be deleted!</span>';
        }
    }

    // Now we will migrate the object type images.
    $g_migration_log[] = '<span class="bold">2. Move uploaded object type images:</span>';
    $oldObjectTypeImagesPath = "{$idoitRootPath}images/objecttypes/";
    $newObjectTypeImagesPath = "{$idoitRootPath}upload/images/{$tenantId}/object-type/images/";

    foreach(glob($oldObjectTypeImagesPath . '*') as $oldObjectTypeImagePath) {
        if (is_dir($oldObjectTypeImagePath)) {
            continue;
        }

        // Get the filename.
        $imageFilename = basename($oldObjectTypeImagePath);

        if (in_array($imageFilename, $coreObjectTypeImages, true)) {
            continue;
        }

        $newObjectTypeImagePath = "{$newObjectTypeImagesPath}{$imageFilename}";

        if (!is_dir($newObjectTypeImagesPath) && !mkdir($newObjectTypeImagesPath, 0775, true)) {
            $g_migration_log[] = '<span class="indent text-red"><strong>Attention!</strong> The new image folder ' . $newObjectTypeImagesPath . ' could not be created, due to missing rights!</span>';
            continue;
        }

        if (rename($oldObjectTypeImagePath, $newObjectTypeImagePath)) {
            $g_migration_log[] = 'Moved <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $oldObjectTypeImagePath) . '</span><br />To <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $newObjectTypeImagePath) . '</span>';

            // @todo  Migrate database entries.
        } else {
            $g_migration_log[] = '<span class="ident text-red"><strong>Attention!</strong> The object type image <span class="text-monospace">' . str_replace($idoitRootPath, '', $oldObjectTypeImagePath) . '</span> could not be moved to <span class="text-monospace">' . str_replace($idoitRootPath, '', $newObjectTypeImagePath) . '</span>!</span>';
        }
    }

    // At last we will migrate the object type icons.
    $g_migration_log[] = '<span class="bold">3. Move uploaded object type icons:</span>';
    $oldObjectTypeIconsPath = "{$idoitRootPath}images/icons/silk/";
    $newObjectTypeIconsPath = "{$idoitRootPath}upload/images/{$tenantId}/object-type/icons/";

    foreach(glob($oldObjectTypeIconsPath . '*') as $oldObjectTypeImagePath) {
        if (is_dir($oldObjectTypeImagePath)) {
            continue;
        }

        // Get the filename.
        $iconFilename = basename($oldObjectTypeImagePath);

        if (in_array($iconFilename, $coreObjectTypeIcons, true)) {
            continue;
        }

        $newObjectTypeImagePath = "{$newObjectTypeIconsPath}{$iconFilename}";

        if (!is_dir($newObjectTypeIconsPath) && !mkdir($newObjectTypeIconsPath, 0775, true)) {
            $g_migration_log[] = '<span class="indent text-red"><strong>Attention!</strong> The new image folder ' . $newObjectTypeIconsPath . ' could not be created, due to missing rights!</span>';
            continue;
        }

        if (rename($oldObjectTypeImagePath, $newObjectTypeImagePath)) {
            $g_migration_log[] = 'Moved <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $oldObjectTypeImagePath) . '</span><br />To <span class="text-monospace text-green">' . str_replace($idoitRootPath, '', $newObjectTypeImagePath) . '</span>';

            $newObjectTypeIconPath = $daoTenant->convert_sql_text(basename($newObjectTypeImagePath));
            $oldObjectTypeIconPath = $daoTenant->convert_sql_text(str_replace($idoitRootPath, '', $oldObjectTypeImagePath));

            // Migrate the entries in the database.
            $sql = "UPDATE isys_obj_type
                SET isys_obj_type__icon = {$newObjectTypeIconPath}
                WHERE isys_obj_type__icon LIKE {$oldObjectTypeIconPath};";

            if (! $daoTenant->update($sql) && $daoTenant->apply_update()) {
                $g_migration_log[] = '<span class="indent text-red"><strong>Attention!</strong> Updating the object type icon failed:</span>';
            }
        } else {
            $g_migration_log[] = '<span class="ident text-red"><strong>Attention!</strong> The object type icon <span class="text-monospace">' . str_replace($idoitRootPath, '', $oldObjectTypeImagePath) . '</span> could not be moved to <span class="text-monospace">' . str_replace($idoitRootPath, '', $newObjectTypeImagePath) . '</span>!</span>';
        }
    }

    $this->migration_done($migrationIdentifier);
}
