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



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

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

$menu_code = 'main_menu';

$res = $db->query("SELECT id FROM publish_menu WHERE title=str:title", $menu_code);

if (!$res->hasData())
{
	$menu_items = array(
		array('Home', '/intranet/main/'),
		array('Edit this menu', '/intranet/publish/menu_builder.php', true),
	);

	$db->query(new \Claromentis\Core\DAL\QueryInsert('publish_menu',
	    array(
		    'str:title' => $menu_code,
		    'int:type' => 6,
		    'int:date_created' => time(),
		    'str:menu_comment' => 'Main menu',
		    'int:folder_id' => 0,
		    'int:menu_page_id' => 0,
		    'int:menu_folder_id' => 0,
		    'int:menu_trail_page_id' => 0,
		    'str:menu_trail_sep' => '>',
		    'int:menu_trail_show_home' => 0,
		    'int:sync_visib_mode' => 1,
		    'int:menu_sitemap_page_id' => 0,
		    'int:sitemap_flag' => 0,
		    'int:location' => 2, // MENU_LOCATION_INTRANET
		    'int:depth_limit' => 3,
	    )));

	$menu_id = $db->insertId();

	if (!$menu_id)
	{
		$migrations->Log("Failed creating main menu");
	} else
	{
		$perms = new Permissions(PERM_CLASS_PUBLISH_MENU, $menu_id);
		$perms->Add(PERM_VIEW, PERM_OCLASS_INDIVIDUAL, 1); // give admin rights to edit menu
		$perms->Save();

		$order_index = 1;
		foreach ($menu_items as $item_info)
		{
			$node_perms = new UnifiedPermissions();
			if (isset($item_info[2]) && $item_info[2]) // admin only item
				$node_perms->Add(PERM_VIEW, PERM_OCLASS_INDIVIDUAL, 1);
			else
				$node_perms->Add(PERM_VIEW, PERM_OCLASS_ALL);
			$node_perms->Save();
			$perm_id = $perms->id;

			$db->query(new \Claromentis\Core\DAL\QueryInsert('publish_menunode', array(
			    'int:menu_id' => $menu_id,
			    'int:parent_id' => 0,
			    'int:order_index' => $order_index++,
			    'str:title' => $item_info[0],
			    'str:url' => $item_info[1],
			    'int:visible' => 1,
			    'int:page_id' => 0,
			    'int:type' => 2, // MENU_NODE_LINK
			    'int:new_window' => 0,
			    'int:perm_id' => $perm_id,
			)));
		}
	}
}

DB_UPDATE_FILE
);


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