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



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

/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();
$db->AddColumn('cln_calendar', 'last_background_sync', "INT_DATE NOT_NULL DEFAULT 0");

DB_UPDATE_FILE
);


$migrations->Run('02_rename_dotenv_claro_env_mode.php', <<<'DB_UPDATE_FILE'
<?php
/**
 * Substitutes `CLARO_ENV_MODE` for `CLARO_ENV` in any .env files it finds at valid file paths.
 *
 * @var \Claromentis\Setup\SetupFacade $migrations
 */

use Claromentis\Core\Services;

$basePath = Services::I()->{'core.base_path'};
$dotenvPaths = ["$basePath/.env", "$basePath/../.env"];

foreach ($dotenvPaths as $dotenvPath) {
	if (is_file($dotenvPath)) {
		$migrations->Log("Found .env file at path $dotenvPath");

		if (!is_readable($dotenvPath)) {
			$migrations->Log(".env file not readable at path $dotenvPath, skipping");
			continue;
		}

		if (!is_writable($dotenvPath)) {
			$migrations->Log(".env file not writable at path $dotenvPath, skipping");
			continue;
		}

		$dotenv = file_get_contents($dotenvPath);
		$dotenv = str_replace("CLARO_ENV_MODE", "CLARO_ENV", $dotenv);
		file_put_contents($dotenvPath, $dotenv);

		$migrations->Log("Updated CLARO_ENV_MODE to CLARO_ENV at path $dotenvPath");
	} else {
		$migrations->Log(".env file not found at path $dotenvPath");
	}
}

DB_UPDATE_FILE
);


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