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



$migrations->Run('01_create_topics_for_existing_projects.php', <<<'DB_UPDATE_FILE'
<?php

use Claromentis\Setup\SetupFacade;

/** @var SetupFacade $migrations */
$db = $migrations->GetDb();


/**
 * Find any projects that don't have default topics or have them but the comments not copied over yet
 */
$projects_result = $db->query("SELECT id FROM projects_project WHERE id NOT IN (SELECT distinct project_id FROM projects_topic) OR id IN (SELECT distinct object_id FROM discussions WHERE aggregation = 121)");

while ($result = $projects_result->fetchArray())
{
	$project_id = (int)$result['id'];
	$default_title = lmsg("projects.topic.default_topic_name");

	// Check for an existing default topic
	[$topic_id] = $db->query_row('SELECT id FROM projects_topic WHERE project_id eq:int:project_id AND title eq:str:title', $project_id, $default_title);

	if ($topic_id === null)
	{
		$now = new \Date();
		$now = $now->getDate(DATE_FORMAT_TIMESTAMP);
		/**
		 * Create a default Topic for each Project if one didn't exist
		 */
		$db->query(
			"INSERT INTO projects_topic(project_id, title, created, modified) VALUES (int:pid, str:title, int:created, int:modified)",
			$project_id,
			$default_title,
			$now,
			$now
		);
		$topic_id = $db->insertId();
	}

	/**
	 * Move all comments/discussions from the Project to the new Topic
	 * 121: Claromentis/Projects/Permissions::PROJECT_AGGREGATION
	 * 155: Claromentis/Projects/Entity/ProjectTopic::AGGREGATION
	 * */
	$db->query(
		"UPDATE discussions SET aggregation=155, object_id=int:tid WHERE aggregation=121 AND object_id=int:pid",
		$topic_id,
		$project_id
	);
}

DB_UPDATE_FILE
);


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