<?php

global $g_comp_database, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = 'migrate_calculated_guarantee_date';

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Guarantee date migration has already been processed</span>';
} else {
    $g_migration_log[] = '<span class="bold">Migrate calculated guarantee date to a physical date ...</span>';

    $dao = new \isys_cmdb_dao_category_g_accounting($g_comp_database);

    $calculateGuaranteeDate = function ($data) use ($dao) {
        if ($data["isys_catg_accounting_list__guarantee_period"]
            && $data["isys_guarantee_period_unit__id"]
            && $data['isys_catg_accounting_list__guarantee_period_base']
        ) {
            switch ($data['isys_catg_accounting_list__guarantee_period_base']) {
                case \isys_cmdb_dao_category_g_accounting::C__GUARANTEE_PERIOD_BASE__DELIVERY_DATE:
                    $date = strtotime($data['isys_catg_accounting_list__delivery_date']);
                    break;
                case \isys_cmdb_dao_category_g_accounting::C__GUARANTEE_PERIOD_BASE__ORDER_DATE:
                    $date = strtotime($data['isys_catg_accounting_list__order_date']);
                    break;
                case \isys_cmdb_dao_category_g_accounting::C__GUARANTEE_PERIOD_BASE__DATE_OF_INVOICE:
                    $date = strtotime($data['isys_catg_accounting_list__acquirementdate']);
                    break;
                default:
                    $date = time();
                    break;
            }
            return date(
                'Y-m-d',
                $dao->calculate_guarantee_date(
                    $date,
                    $data["isys_catg_accounting_list__guarantee_period"],
                    $data["isys_guarantee_period_unit__id"]
                )
            );
        }
        return null;
    };

    $result = $dao->get_data();
    $count = 0;
    while ($row = $result->get_row()) {
        $guaranteeDate = $calculateGuaranteeDate($row);
        $g_migration_log[] = "Guarantee date for {$row['isys_obj__title']} has been migrated and calculated with {$guaranteeDate}.";
        $update = 'UPDATE isys_catg_accounting_list SET isys_catg_accounting_list__guarantee_date = ' . $dao->convert_sql_text($guaranteeDate) . '
            WHERE isys_catg_accounting_list__id = ' . $dao->convert_sql_id($row['isys_catg_accounting_list__id']) . ';';
        $dao->update($update);
        $count++;
    }
    $dao->apply_update();

    $g_migration_log[] = '<span class="bold text-green">' . $count . ' accounting entries have been updated.</span>';

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

    $this->migration_done($migrationIdentifier);
}
