<?php
$_db_migration_to = '39.32'; // 8.13.40
if (!isset($migrations) || !is_object($migrations))
	die("This file cannot be executed directly");
$migrations->CheckValid($_db_migration_to);
//===========================================================================================



$migrations->Run('20240201_hd_issues_add_indexes.php', <<<'DB_UPDATE_FILE'
<?php

/**
 * BT-4476 Tickets loading time optimizations in IC
 *
 * @var \Claromentis\Setup\SetupFacade $migrations
 */
$db = $migrations->GetDb();

// Create indexes to improve loading time for tickets loading time in IC
$db->CreateIndex('hd_issue', 'idx_project_id_in_project', 'project_id', 'id_in_project');

DB_UPDATE_FILE
);


$migrations->Run('20240118125500_update_news_articles_to_notified_before_date.php', <<<'DB_UPDATE_FILE'
<?php

/**
 * BT-4457
 * 
 * This migration solves a potential backlog of notifications being sent.
 * 
 * There was a bug where creating a new News Article, setting the Publish Date to the future, 
 * ticking the "Send notification to all users with view rights" option, 
 * and omitting text in the short summary, results in user notifications failing to trigger when the article becomes live.
 * 
 * There could be a possibility that this bug went unnoticed for a while and there's many News Articles ready to send a notification
 * but couldn't send due to the bug.
 * 
 * We only want the recent News Articles to send a notifcation.
 */

use Claromentis\Core\DAL;

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

$date = new Date();
$date->modify('-7 days');
$date->setTime(0, 0, 0);

$logger->notice("Disabling notifications for News Articles published before {$date->format('Y-m-d 00:00')}.");

$database = $migrations->GetDb();

try {
	$database->DoTransaction(function (DAL\Interfaces\DbInterface $database) use ($date) {
		$query = new DAL\Query('UPDATE news SET notify_readers=0, subscribers_notified=1 WHERE (notify_readers=1 OR subscribers_notified=0) AND date_start < int:date_start');
		$query->Bind('date_start', $date->getDate());
		$database->query($query);
	});
} catch (DAL\Exceptions\TransactionException $exception) {
	$logger->error("Migration failed to run, reason below:");
	$logger->error($exception);

	// Rethrow the exception to ensure the migration and upgrade fails
	throw $exception;
}

$logger->notice("Migration ran successfully.");

DB_UPDATE_FILE
);


//===========================================================================================
$migrations->SetVersion('39.32');
