<?php

/**
 * i-doit - Updates
 *
 * Migrating reports to each tenant
 *
 * @package     i-doit
 * @subpackage  Update
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */


/**
 * @var $g_comp_database isys_component_database
 */
global $g_dirs, $g_comp_database, $g_comp_database_system;

// Set migrationId
$g_migration_identifier = "object_picture_visibility_migration";

// Check whether migration was executed before
if ($this->is_migration_done($g_migration_identifier)) {
    $g_migration_log[] = '<span class="bold">Object pictures have already been migrated.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting migration of all object_pictures.</span>';

    $picturesDir = $g_dirs['fileman']['image_dir'];

    $images = glob($picturesDir . '/*.*');

    if (count($images) !== 0) {
        // Copy all available pictures into folders for every tenant
        $tenants = $g_comp_database_system->retrieveArrayFromResource($g_comp_database_system->query('SELECT isys_mandator__id FROM isys_mandator WHERE TRUE'));

        foreach ($tenants as $tenant) {
            $tenantPictureDirectory = $picturesDir . '/' . $tenant['isys_mandator__id'];
            if (!file_exists($tenantPictureDirectory) && !mkdir($tenantPictureDirectory) && !is_dir($tenantPictureDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $tenantPictureDirectory));
            }

            // Move all images into tenant directory
            foreach ($images as $image) {
                copy($image, $tenantPictureDirectory . '/' . basename($image));
            }
        }

        // Remove images from image dir root
        foreach ($images as $image) {
            unlink($image);
        }
    }

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

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