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



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

/** @var $migrations \Claromentis\Setup\SetupFacade */
$panels = $migrations->GetAdminPanelCreator();
$panels->Enable('communication');

DB_UPDATE_FILE
);


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

use Claromentis\Core\DAL;


// infobar_menu_item
$table_descr = array(
	'id' => "IDENTITY",
	'menu_type' => 'INT DEFAULT 0',
	'item_type' => 'INT DEFAULT 0',
	'user_id' => 'INT DEFAULT 0',
	'title' => "VARCHAR(255) NULL",
	'url' => "VARCHAR(1024) NULL",
	'display_order' => "INT NULL",
	'new_window' => "INT NULL",
	'is_visible' => "BOOL DEFAULT 1",
	'css_class' => "VARCHAR(100) DEFAULT NULL",
);

$db->CreateTable('infobar_menu_item', $table_descr, true);


$db->query("UPDATE permissions SET object_id=-object_id WHERE class_id=27"); // 27 is PERM_CLASS_INFOBAR

$res = $db->query("SELECT * FROM infobar_menu");
while ($info = $res->fetchArray())
{
	$query = new DAL\QueryInsert('infobar_menu_item', [
		'int:menu_type' => 0,
		'int:item_type' => 0,
		'int:user_id' => 0,
		'str:title' => $info['name'],
		'str:url' => $info['link'],
		'int:display_order' => $info['displayorder'],
		'int:new_window' => $info['new_window'],
		'int:is_visible' => 1,
		'str:css_class' => ''
	]);

	$db->query($query);

	$new_id = $db->insertId();

	if ($new_id)
		$db->query("UPDATE permissions SET object_id=int:new_id WHERE object_id=int:minus_old_id AND class_id=27", $new_id, -$info['id']);
}

DB_UPDATE_FILE
);


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

$db->DropTable('infobar_menu');

DB_UPDATE_FILE
);


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

use Claromentis\Core\DAL;

list($menu_id) = $db->query_row("SELECT id FROM publish_menu WHERE title eq:str:title", 'applications');

if ($menu_id)
{
	$lmsg_str = function ($str)
	{
		$matches = null;
		if (strlen($str) > 100 || !preg_match('/^@\{([\d\w\._]+)(\|([^}]*))?\}$/', trim($str), $matches))
			return $str;
		if (isset($matches[3]))
			return $matches[3];
		return $str;
	};


	$ids_map = [];
	$res = $db->query("SELECT * FROM publish_menunode WHERE menu_id=int:menu_id AND parent_id=0 ORDER BY order_index", $menu_id);
	$display_order = 1;
	while ($node_info = $res->fetchArray())
	{
		$db_data = [
			'str:title' => $lmsg_str($node_info['title']),
			'str:url' => $node_info['url'],
			'int:display_order' => $display_order++,
			'int:new_window' => $node_info['new_window'],
			'int:menu_type' => 1, // 1 is InfobarMenuType::APPLICATIONS
			'int:item_type' => 0, // 0 is ItemType::LINK
			'int:is_visible' => $node_info['visible'],
			'str:css_class' => $node_info['css_class'],
		];

		if ($node_info['css_class'] == 'divider')
			$db_data['int:item_type'] = 2; // 2 is ItemType::DIVIDER
		elseif (substr($node_info['css_class'], 0, 4) == 'app-')
		{
			$app_code = substr($node_info['css_class'], 4);
			if ($app_code == 'forums')
				$app_code = 'forum';
			elseif ($app_code == 'roombooking')
				$app_code = 'rooms';
			elseif ($app_code == 'auditmanager')
				$app_code = 'audit';
			elseif ($app_code == 'policymanager')
				$app_code = 'policy';
			elseif ($app_code == 'holidayplanner')
				$app_code = 'holidays';
			elseif ($app_code == 'menubuilder')
				$app_code = 'menu';
			elseif ($app_code == 'statistics')
				$app_code = 'stat';
			elseif ($app_code == 'learning')
				$app_code = 'education';
			if (in_array($app_code, [
				'blog',
				'calendar',
				'communication',
				'discuss',
				'documents',
				'expenses',
				'forum',
				'holidays',
				'gallery',
				'infocapture',
				'innovate',
				'knowledgebase',
				'menu',
				'news',
				'people',
				'publish',
				'rooms',
				'mail',
				'search',
				'stat',
				'admin',
			])) {
				$db_data['str:url'] = $app_code;
				$db_data['int:item_type'] = 1; // 1 is ItemType::APPLICATION
			}
		}

		$query = new DAL\QueryInsert('infobar_menu_item', $db_data);

		$db->query($query);

		$new_id = $db->insertId();

		if ($new_id)
		{
			$db->query("INSERT INTO permissions (class_id, object_id, perm_owner_class_id, perm_owner_id, rights) 
						SELECT int:new_class_id, int:new_object_id, perm_owner_class_id, perm_owner_id, rights FROM permissions
						WHERE class_id=19 AND object_id=int:old_oid",
			           27 /*PERM_CLASS_INFOBAR */, $new_id, (int)$node_info['perm_id']);
		}
	}
}

DB_UPDATE_FILE
);


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

$app_classes = array(
	'app-admin'             => 'glyphicons-settings',
	'app-auditmanager'      => 'glyphicons-security-camera',
	'app-blog'              => 'glyphicons-edit',
	'app-calendar'          => 'glyphicons-calendar',
	'app-communication'     => 'glyphicons-bullhorn',
	'app-courseplanner'     => 'glyphicons-book-open',
	'app-crm'               => 'glyphicons-group',
	'app-discuss'           => 'glyphicons-conversation',
	'app-documents'         => 'glyphicons-file',
	'app-expenses'          => 'glyphicons-coins',
	'app-forums'            => 'glyphicons-comments',
	'app-gallery'           => 'glyphicons-inbox-in',
	'app-holidayplanner'    => 'glyphicons-plane',
	'app-home'              => 'glyphicons-home',
	'app-infocapture'       => 'glyphicons-random',
	'app-innovate'          => 'glyphicons-conversation',
	'app-knowledgebase'     => 'glyphicons-tree-deciduous',
	'app-learning'          => 'glyphicons-education',
	'app-menubuilder'       => 'glyphicons-list',
	'app-news'              => 'glyphicons-bullhorn',
	'app-people'            => 'glyphicons-address-book',
	'app-policymanager'     => 'glyphicons-settings',
	'app-publish'           => 'glyphicons-global',
	'app-roombooking'       => 'glyphicons-clock',
	'app-search'            => 'glyphicons-search',
	'app-statistics'        => 'glyphicons-stats',
);


foreach ($app_classes as $class => $glyph)
{
	$db->query("UPDATE infobar_menu_item 
		SET css_class=str:glyph 
		WHERE css_class=str:class",
		$glyph,
		$class);
}


DB_UPDATE_FILE
);


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

$db->AddColumn('ERMS_data', 'is_draft', "INT NOT_NULL DEFAULT 0");

DB_UPDATE_FILE
);


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

$db->AddColumn('ERMS_data', 'latest_version_id', "INT NOT_NULL DEFAULT 0");
// All existing documents are 'live' so the version ids will initially be the same
$db->query('UPDATE ERMS_data SET latest_version_id=primary_version_id WHERE latest_version_id=0');

DB_UPDATE_FILE
);


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