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



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

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

@$db->DropIndex('discussions', 'idx_aggregation_parent_id_object_id_timestamp');
$db->CreateIndex('discussions', 'idx_aggregation_parent_id_object_id_timestamp', 'aggregation', 'parent_id', 'object_id', 'timestamp');

DB_UPDATE_FILE
);


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

/**
 * Migration to repair incorrect Theme URLs introduced in the Migration "01_theme_code_repair".
 * Reads existing Themes, checks for the existance of their files and if absent, checks alternatives and links if existing.
 */

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

$cdn = \Claromentis\Core\Services::I()->GetCDN();

if (!function_exists('rebuildThemeAssetUrl'))
{
	/**
	 * Given a URL Path,
	 * rebuilds it if the file is identified as missing and the expected alternative (based on Theme Code) does exist.
	 * Returns the original URL Path if not.
	 *
	 * @param string                             $url
	 * @param string                             $themeCode
	 * @param \Claromentis\Core\CDN\CDNInterface $cdn
	 * @return string
	 * @throws \Claromentis\Core\CDN\CDNSystemException
	 * @throws Exception If the URL is invalid
	 */
	function rebuildThemeAssetUrl(string $url, string $themeCode, \Claromentis\Core\CDN\CDNInterface $cdn): string
	{
		$urlPath = parse_url($url, PHP_URL_PATH);
		if (!is_string($urlPath))
		{
			throw new Exception("Theme '$themeCode' has an invalid asset url '$url'");
		}
		$urlPathArray = explode('/', $urlPath);
		if (count($urlPathArray) >= 2)
		{
			$filename    = array_pop($urlPathArray);
			$themeFolder = array_pop($urlPathArray);
			if (!$cdn->Exists("/theme/$themeFolder/$filename") && $cdn->Exists("/theme/{$themeCode}/$filename"))
			{
				$url = $cdn->GetUrl("/theme/{$themeCode}/$filename");
			}
		}

		return $url;
	}
}

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

foreach ($themes as $id => $theme)
{
	$modified = false;
	if (isset($theme['style']['logo_url']) && is_string($theme['style']['logo_url']))
	{
		$rebuiltThemePath = rebuildThemeAssetUrl($theme['style']['logo_url'], $theme['code'], $cdn);
		if ($rebuiltThemePath !== $theme['style']['logo_url'])
		{
			$migrations->Log("Theme {$theme['code']} Logo URL updated from {$theme['style']['logo_url']} to $rebuiltThemePath");
			$theme['style']['logo_url'] = $rebuiltThemePath;
			$modified                   = true;
		}
	}
	if (isset($theme['style']['page_bg_image']) && is_array($theme['style']['page_bg_image']))
	{
		foreach ($theme['style']['page_bg_image'] as $offset => $pageBgImage)
		{
			if (is_string($pageBgImage))
			{
				$rebuiltThemePath = rebuildThemeAssetUrl($pageBgImage, $theme['code'], $cdn);
				if ($rebuiltThemePath !== $pageBgImage)
				{
					$migrations->Log("Theme {$theme['code']} Background Image updated from {$pageBgImage} to $rebuiltThemePath");
					$theme['style']['page_bg_image'][$offset] = $rebuiltThemePath;
					$modified                                 = true;
				}
			}
		}
	}
	if (isset($theme['style']['favicon']) && is_array($theme['style']['favicon']))
	{
		foreach ($theme['style']['favicon'] as $offset => $favIcon)
		{
			if (is_string($favIcon))
			{
				$rebuiltThemePath = rebuildThemeAssetUrl($favIcon, $theme['code'], $cdn);
				if ($rebuiltThemePath !== $favIcon)
				{
					$migrations->Log("Theme {$theme['code']} FavIcon updated from {$favIcon} to $rebuiltThemePath");
					$theme['style']['favicon'][$offset] = $rebuiltThemePath;
					$modified                           = true;
				}
			}
		}
	}

	if ($modified)
	{
		$db->query("UPDATE theme SET style = str:style WHERE id = int:id", json_encode($theme['style']), $id);
	}
}


DB_UPDATE_FILE
);


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