<?php

namespace WKO\Model;

use WKO\Helpers\Config;
use WKO\Model\Migration\AddInstallmentDisplayColumn;
use WKO\Model\Migration\AddProductsAndCategoriesColumn;
use WKO\Model\Repository\InstallmentRules;

class Bootstrap
{
	const DB_VERSION_OPTION = 'wko_koin_db_version';

	public array $tables = [
		InstallmentRules::class
	];

	public array $migrations = [
		'1.0.1' => [
			AddInstallmentDisplayColumn::class
		],
		'1.0.2' => [
			AddProductsAndCategoriesColumn::class
		]
	];

	public function initialize(): void
	{
		$this->tables();
		$this->runMigrations();
	}

	public function uninstall(): void
	{
		foreach ($this->tables as $table) {
			if (class_exists($table)) {
				$t = new $table;
				$t->down();
			}
		}
	}

	private function tables(): void
	{
		foreach ($this->tables as $table) {
			if (class_exists($table)) {
				$t = new $table;
				$t->up();
			}
		}
	}

	private function runMigrations(): void
	{
		$currentVersion = get_option(self::DB_VERSION_OPTION, '1.0.0');
		$targetVersion = Config::_db_version();

		if (version_compare($currentVersion, $targetVersion, '>=')) {
			return;
		}

		$versions = array_keys($this->migrations);
		usort($versions, 'version_compare');

		foreach ($versions as $version) {
			if (version_compare($currentVersion, $version, '>=')) {
				continue;
			}

			foreach ($this->migrations[$version] as $migrationClass) {
				if (class_exists($migrationClass)) {
					$migration = new $migrationClass;
					$migration->run();
				}
			}
		}
	}
}
