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



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

/**
 * Remove the Publish plugin and installation record.
 *
 * @var \Claromentis\Setup\SetupFacade $migrations
 */
$migrations->plugins()->remove('publish');
$migrations->GetDb()->query("DELETE FROM db_installed WHERE application='publish'");

DB_UPDATE_FILE
);


$migrations->Run('02_remove_mail_plugin.php', <<<'DB_UPDATE_FILE'
<?php

/**
 * Remove the Mail plugin and installation record.
 *
 * @var \Claromentis\Setup\SetupFacade $migrations
 */
$migrations->plugins()->remove('mail');
$migrations->GetDb()->query("DELETE FROM db_installed WHERE application='mail'");

DB_UPDATE_FILE
);


$migrations->Run('03_convert_publish_menus.php', <<<'DB_UPDATE_FILE'
<?php
/**
 * This migration converts all Publish Menus to Intranet Menus.
 *
 * Publish Menus inherit their permissions from their associated Publish Folder, so in this migration we copy those
 * permissions across if possible. If this fails, Menu Builder administrators can set permissions for the menus.
 *
 * @var \Claromentis\Setup\SetupFacade $migrations
 */

use Claromentis\Core\Acl\AclRepository;
use Claromentis\Core\Services;

/**
 * @see Claromentis\Menu\MenuLocation::PUBLISH
 */
$MENU_LOCATION_PUBLISH = 1;

/**
 * @see Claromentis\Menu\MenuLocation::INTRANET
 */
$MENU_LOCATION_INTRANET = 2;

/**
 * @see PERM_CLASS_PUBLISH_MENU
 */
$PERM_CLASS_PUBLISH_MENU = 48;

/**
 * @see PERM_VIEW
 */
$PERM_VIEW = 1;

// Load services
$database = $migrations->GetDb();
$logger   = $migrations->getLogger();

/** @var AclRepository $aclRepository */
$aclRepository = Services::I()->{AclRepository::class};

// Load Publish menus
$result = $database->query("SELECT id, title FROM publish_menu WHERE location = $MENU_LOCATION_PUBLISH");
$menus  = [];

while ([$menuId, $menuTitle] = $result->fetchRow()) {
	$menus[(int) $menuId] = $menuTitle;
}

$menuNumber = 0;
$menuCount  = count($menus);

// We hope that there aren't too many Publish menus in a single system; we're going to load and update them one by one
foreach ($menus as $menuId => $menuTitle) {
	$menuNumber++;
	$logger->notice("[$menuNumber/$menuCount] Converting Publish Menu \"$menuTitle\" (ID #$menuId) to Intranet Menu");
	$logger->info("  Loading menu #$menuId and its ACL");

	// Load the menu, grab its folder ID, and convert the menu (set location, unset folder ID)
	$menu = new \Claromentis\Menu\PublishMenu();
	$menu->Load($menuId);
	$menu->SetLocation($MENU_LOCATION_INTRANET);
	$folderId = $menu->GetFolderId();
	$menu->SetFolderId(0);
	$menu->Save();

	// Load the folder, copy menu permissions from the associated Publish Folder
	$logger->info("  Loading Publish folder #$folderId");

	$folder = new PublishFolder();
	$folder->Load($folderId, true);

	if (!$folder->IsError()) {
		$logger->info("  Copying permissions from Publish Folder #$folderId to Menu #$menuId");
		$folderAcl = $folder->GetAcl();
		$menuAcl   = $folderAcl->CreateCopy($PERM_CLASS_PUBLISH_MENU, $menuId);
		$aclRepository->Save($menuAcl);
	} else {
		$logger->warning("  Failed to load Publish Folder #$folderId for Menu \"$menuTitle\", skipping copying permissions");
	}
}

DB_UPDATE_FILE
);


$migrations->Run('04_delete_news_announcements.php', <<<'DB_UPDATE_FILE'
<?php

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

/** @see AGGREGATION_NEWS */
$AGGREGATION_NEWS = 21;

/** @see \Claromentis\People\Entity\User::AGGREGATION */
$AGGREGATION_USER = 27;

/** @see PERM_CLASS_NEWS */
$PERM_CLASS_NEWS = 5;

// Collect legacy News Announcement IDs
$announcementIds = [];
$announcementIds = $database->query('SELECT id FROM news WHERE headline = 0')->fetchAllValues();

if (!empty($announcementIds)) {
	$announcementCount = count($announcementIds);
	$logger->notice("Deleting $announcementCount legacy News Announcements");

	// Drop News Announcements from: News, News Translations, Permissions, and Trash Can
	$database->query('DELETE FROM news WHERE id IN in:int:ids', $announcementIds);
	$database->query('DELETE FROM news_translations WHERE news_id IN in:int:ids', $announcementIds);
	$database->query('DELETE FROM permissions WHERE class_id = int:class_id AND object_id IN in:int:ids', $PERM_CLASS_NEWS, $announcementIds);
	$database->query('DELETE FROM trash_can WHERE aggregation = int:aggregation AND obj_id IN in:int:ids', $AGGREGATION_NEWS, $announcementIds);
} else {
	$migrations->getLogger()->notice('No legacy News Announcements found to delete');
}

// Drop all News Trash Can objects with an `orig_location` of "Announcement" for good measure (very convenient)
$database->query('DELETE FROM trash_can WHERE aggregation = int:aggregation AND orig_location = str:location', $AGGREGATION_NEWS, 'Announcement');

// Drop "viewed announcements" User metadata ('announcements' key)
$database->query('DELETE FROM metadata_simple WHERE aggregation = int:aggregation AND name = str:metadata_key', $AGGREGATION_USER, 'announcements');

DB_UPDATE_FILE
);


$migrations->Run('04_remove_surveys_polls_legacy.php', <<<'DB_UPDATE_FILE'
<?php

$PERM_CLASS_SURVEY_LEGACY = 6;
$PERM_CLASS_SURVEY_CAT    = 45;

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

$db->query('DELETE FROM permissions WHERE class_id = int:class_id', $PERM_CLASS_SURVEY_LEGACY);
$db->query('DELETE FROM permissions WHERE class_id = int:class_id', $PERM_CLASS_SURVEY_CAT);

$logger->notice("Removing Survey (legacy) tables");

// drop all tables related to Survey (legacy)
$db->DropTable('survey');
$db->DropTable('survey_categories');
$db->DropTable('survey_options');
$db->DropTable('survey_questions');
$db->DropTable('survey_smileys');
$db->DropTable('survey_smiley_packs');
$db->DropTable('survey_voters');

DB_UPDATE_FILE
);


$migrations->Run('05_trash_can_index.php', <<<'DB_UPDATE_FILE'
<?php
/** @var \Claromentis\Setup\SetupFacade $migrations */
$database = $migrations->GetDb();

// FRAM-163 Minor performance improvements for Trash Can queries
$database->CreateIndex('trash_can', 'idx_aggregation_obj_id', 'aggregation', 'obj_id');
$database->CreateIndex('trash_can', 'idx_deletion_date', 'deletion_date');

DB_UPDATE_FILE
);


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