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



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

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

$db->AddColumn('hd_project', 'view_stats_rights', 'INT NOT_NULL DEFAULT 0');

DB_UPDATE_FILE
);


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

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

$roles_bitmasks = [];
$result = $db->query("SELECT bitmask, project_id FROM hd_role");

while ($row = $result->fetchArray())
{
	$roles_bitmasks[$row['project_id']][] = (int) $row['bitmask'];
}


$result = $db->query("SELECT id, manage_rights FROM hd_project hdp");

while ($row = $result->fetchArray())
{
	$project_id = (int) $row['id'];

	$bitmask = 0;
	$manage_rights = (int) $row['manage_rights'];

	if ($manage_rights > 0)
	{
		$project_roles_bm = $roles_bitmasks[$project_id] ?? [];
		foreach ($project_roles_bm as $role_bm)
		{
			$res = $role_bm & $manage_rights;
			if ($res > 0)
			{
				$bitmask |= $role_bm;
			}
		}
	}

	if ($bitmask > 0)
	{
		$db->query('UPDATE hd_project SET view_stats_rights = int:view_stats_rights WHERE id = int:id', $bitmask, $project_id);
	}
}


DB_UPDATE_FILE
);


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