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



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

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

$db->AddColumn('pages_site', 'is_deleted', 'BOOL NOT_NULL DEFAULT 0');
$db->AddColumn('pages_menu_item', 'is_deleted', 'BOOL NOT_NULL DEFAULT 0');

DB_UPDATE_FILE
);


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

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

$table_descr = array(
	'id'	=>	"IDENTITY",
	'obj_id'	=>	"INT NULL",
	'aggregation'	=>	"INT NOT_NULL",
	'user_id'	=>	"INT NOT_NULL",
	'deletion_date'	=>	"INT NOT_NULL",
	'title'	=>	"VARCHAR(255) NULL",
	'orig_location'	=>	"VARCHAR(255) NULL",
	'description'	=>	"VARCHAR_MAX NULL",
);

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

DB_UPDATE_FILE
);


$migrations->Run('03_add_site_id_to_trash_can_table.php', <<<'DB_UPDATE_FILE'
<?php

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

$db->AddColumn('pages_trash_can', 'site_id', 'INT NOT_NULL');

// Converting deleted sites is easy, just copy the object_id
$db->query('UPDATE pages_trash_can SET site_id = obj_id WHERE aggregation = 157');

// Look up site_id for deleted pages
$db->query('UPDATE pages_trash_can ptc JOIN pages_menu_item mi ON ptc.obj_id = mi.id SET ptc.site_id = mi.site_id WHERE ptc.aggregation = 145');

DB_UPDATE_FILE
);


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

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

$db->AddColumn('pages_trash_can', 'type', 'INT NOT_NULL');

$db->query('UPDATE pages_trash_can SET type = 1 WHERE aggregation = 157');  // Site
$db->query('UPDATE pages_trash_can SET type = 2 WHERE aggregation = 145');  // Page

DB_UPDATE_FILE
);


$migrations->Run('05_convert_site_rights.php', <<<'DB_UPDATE_FILE'
<?php

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

/**
 * Sites in general use now only have a single right with bitmask 1 so all that used the old manage right of 23 can be
 * directly converted. Sites do use three temporary rights during creation but none of these overlap with 23 so this
 * migration will not break those
 *
 * \Claromentis\Pages\Perm::SITE_MANAGE = 1
 * \Claromentis\Pages\Perm::CLASS_SITE = 132
 * \Claromentis\Pages\Perm::CREATOR_PERMS = 23   // Removed site management right
 */
$db->query('UPDATE permissions SET rights = 1 WHERE class_id = 132 AND rights = 23');


DB_UPDATE_FILE
);


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