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



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

/**
 * Updates all Theme's Codes to match the Theme's ID.
 * Updates all references to the Theme's Code in the User table.
 */

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

$cdn = \Claromentis\Core\Services::I()->GetCDN();
$config = $migrations->GetConfigFull('core');
$cfg_guest_vi = $config->Get('cfg_guest_vi');
$cfg_login_vi = $config->Get('cfg_login_vi');

$oldThemeCodes = [];
$results       = $db->query("SELECT id, code FROM theme");
while ($row = $results->fetchArray())
{
	$oldThemeCodes[(int) $row['id']] = $row['code'];
}

$db->DoTransaction(function (\Claromentis\Core\DAL\Interfaces\DbInterface $db) {
	$themeTable      = "theme";
	$themeCodeColumn = "code";
	$theme_id_column = "id";

	$userTable       = 'users';
	$userThemeColumn = 'skin';

	$updateUserTable = "UPDATE $userTable";

	$joinThemes = "INNER JOIN $themeTable ON $userTable.$userThemeColumn = $themeTable.$themeCodeColumn";
	$setColumns = "SET $userTable.$userThemeColumn = $themeTable.$theme_id_column";

	switch ($db->type())
	{
		case "sqlite":
		case "mysql":
			$db->query("$updateUserTable $joinThemes $setColumns");
			break;
		case "mssql":
			$db->query("$updateUserTable $setColumns FROM $userTable $joinThemes");
			break;
		default:
			throw new RuntimeException("Migration '01_them_code_repair' failed; could not generate SQL query due to unrecognised database type");
	}

	$db->query("UPDATE $themeTable SET $themeTable.$themeCodeColumn = $themeTable.$theme_id_column");
});

$config_changed = false;
foreach ($oldThemeCodes as $id => $code)
{
	if ((string) $id !== $code && $cdn->IsDir("/theme/$code"))
	{
		$migrations->Log("Renaming CDN directory '/theme/$code' to '/theme/$id'");
		$cdn->RenameDir("/theme/$code", "/theme/$id");
	}

	if ($code === $cfg_guest_vi)
	{
		$migrations->Log("Updating Core Config 'cfg_guest_vi' from $code to $id");
		$config->Set('cfg_guest_vi', $id);
		$config_changed = true;
	}

	if ($code === $cfg_login_vi)
	{
		$migrations->Log("Updating Core Config 'cfg_login_vi' from $code to $id");
		$config->Set('cfg_login_vi', $id);
		$config_changed = true;
	}
}

if ($config_changed)
{
	$config->Save();
}

DB_UPDATE_FILE
);


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