<?php

/**
 * DMS-20
 *
 * This migration creates a new metadata element `doc_review_reminder_sent` and
 * adds this to the Documents and Folders metadata set.
 */

use Claromentis\Core\DAL;

/** @var \Claromentis\Setup\SetupFacade $migrations */
$logger = $migrations->getLogger();

$logger->notice("Starting migration for DMS-20");

$database = $migrations->GetDb();

$config = $migrations->GetConfigFull();
$docReviewDateConfigValue = $config->get('cfg_review_date_metadata');

try {
    $logger->notice("Loading metadata sets for documents and folders.");
    $documentsMetadataSet = MetaFieldFactory::Instance()->GetMetaDataSetByTypeCached(METADATA_SET_DOCUMENT);
    $folderMetadataSet = MetaFieldFactory::Instance()->GetMetaDataSetByTypeCached(METADATA_SET_FOLDER);

    /**
     * @var DynamicMetaFieldPrototype|bool
     */
    $metadataFieldObj = MetaFieldFactory::Instance()->GetPrototypeByKey('doc_review_reminder_sent');

    if (!$metadataFieldObj) {
        $logger->notice("Metadata field 'doc_review_reminder_sent' does not exist. Creating new field.");
        $metadataFieldObj = new DynamicMetaFieldPrototype();
    } else {
        $logger->notice("Metadata field 'doc_review_reminder_sent' already exists. Updating properties.");
    }

    $metadataFieldObj->SetDefaultValue(1);
    $metadataFieldObj->SetMetaType(META_TYPE_INT);
    $metadataFieldObj->SetTitle('Documents Review Reminder');
    $metadataFieldObj->SetName('doc_review_reminder_sent');
    $metadataFieldObj->SetVisible(false);
    $metadataFieldObj->SetRepeatable(false);
    $metadataFieldObj->SetEditable(false);
    $metadataFieldObj->is_system = true;
    $metadataFieldObj->Save();

    $documentsMetadataSet->AddMetaField($metadataFieldObj);
    $folderMetadataSet->AddMetaField($metadataFieldObj);

    $documentsMetadataSet->Save();
    $folderMetadataSet->Save();

    $logger->notice("Metadata field 'doc_review_reminder_sent' applied to documents and folders.");

    $now = new Date();
	$nowTimestamp = $now->getDate(DATE_FORMAT_TIMESTAMP);
	$todayTimestamp = $now->getDate(DATE_FORMAT_DATE_DAY);

    $logger->notice("Querying documents with review dates in the future.");
    $result = $database->query("
        SELECT ml_date.object_id, ml_date.aggregation
            FROM ERMS_metadata_link AS ml_date
        JOIN ERMS_metadata_element AS me_date ON me_date.id = ml_date.element_id
            WHERE me_date.name = str:doc_review_date
			AND (me_date.type = int:meta_type_date AND me_date.intval > int:today) OR (me_date.type = int:meta_type_datetime AND me_date.intval > int:now)
            AND ml_date.aggregation IN (int:aggregation_data, int:aggregation_folder)
    ",
		$docReviewDateConfigValue,
        META_TYPE_DATE,
		$todayTimestamp,
        META_TYPE_DATETIME,
        $nowTimestamp,
        AGGREGATION_DATA,
        AGGREGATION_FOLDER,
    );

    $updatedCount = 0;
    while ($row = $result->fetchArray()) {
        $docId = $row['object_id'];
        $aggregation = $row['aggregation'];

        /**
         * @var ERMSObject|bool $object
         */
        $object = ERMSBrowser::I()->GetERMSObject($docId, $aggregation);

        if (!$object) {
            $logger->warning("ERMSObject with ID {$docId} and aggregation {$aggregation} not found. Skipping.");
            continue;
        }

        $object->metadata->SetValue('doc_review_reminder_sent', 0);
        $object->metadata->SaveValue('doc_review_reminder_sent');
        $updatedCount++;
        $logger->info("Updated 'doc_review_reminder_sent' for object ID {$docId} (aggregation {$aggregation}).");
    }

    $logger->notice("Migration completed successfully. Updated {$updatedCount} objects.");

} catch (Exception $exception) {
    $logger->error("Migration failed for DMS-20: " . $exception->getMessage());
    throw $exception;
}
