<?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_comp_database, $g_comp_database_system;

// Set migrationId
$g_migration_identifier = "import_files_visibility_migration";

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

    if (defined('C__IMPORT__DIRECTORY')) {
        $importDirectory = C__IMPORT__DIRECTORY;
    } else {
        $importDirectory = isys_tenantsettings::get('system.dir.csv-uploads', rtrim(isys_tenantsettings::get('system.dir.import-uploads', BASE_DIR . '/imports/'), '/') . '/');
    }

    $files = glob($importDirectory . '/*.*');

    if (count($files) !== 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) {
            $tenantImportDirectory = $importDirectory . '/' . $tenant['isys_mandator__id'];
            if (!file_exists($tenantImportDirectory) && !mkdir($tenantImportDirectory) && !is_dir($tenantImportDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $tenantImportDirectory));
            }

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

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

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

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