<?php

namespace Planaday\Platform\WordpressConfig\Migrations\Version1;

use Planaday\Config\Course\CourseOptionsEnum;
use Planaday\Config\Course\CourseSettings;
use Planaday\Config\FeatureToggles\FeatureToggleEnum;
use Planaday\Config\FeatureToggles\FeatureToggleSettings;
use Planaday\Config\General\Api\ApiOptionsEnum;
use Planaday\Config\General\GeneralOptionsEnum;
use Planaday\Config\General\GeneralSettings;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\PluginData;

class MigrateTo1_1_0 {
	use Logging;

	public function __construct(
		protected PluginData $pluginData
	) {}

	public function migrate(): void{
		$oldGeneralSettings = get_option($this->pluginData->getFullPrefix() . GeneralSettings::getIndex()) ?? [];
		$existingUser = isset($oldGeneralSettings[GeneralOptionsEnum::API_SETTINGS->value][ApiOptionsEnum::API_KEY->value]);
		$this->logInfo('Existing user: ' . ($existingUser ? 'yes' : 'no'));

		$featureToggles = [
			FeatureToggleEnum::ShortcodeSettings->value => $existingUser
		];
		update_option( $this->pluginData->getFullPrefix() . FeatureToggleSettings::getIndex(), $featureToggles );

		$courseOptions = get_option( $this->pluginData->getFullPrefix() . CourseSettings::getIndex() );

		if (isset ($courseOptions[CourseOptionsEnum::OVERVIEW_SETTINGS->value]['E_LEARNING_COUNTS_AS_START'])){
			$courseOptions[CourseOptionsEnum::GENERAL_SETTINGS->value] ??= [];
			$courseOptions[CourseOptionsEnum::GENERAL_SETTINGS->value][\Planaday\Config\Course\General\GeneralOptionsEnum::E_LEARNING_COUNTS_AS_START->value] =
				$courseOptions[CourseOptionsEnum::OVERVIEW_SETTINGS->value]['E_LEARNING_COUNTS_AS_START'];
			unset($courseOptions[CourseOptionsEnum::OVERVIEW_SETTINGS->value]['E_LEARNING_COUNTS_AS_START']);
		}
		if (isset ($courseOptions[CourseOptionsEnum::OVERVIEW_SETTINGS->value]['INCLUDE_E_LEARNING_DAY_PARTS'])){
			$courseOptions[CourseOptionsEnum::GENERAL_SETTINGS->value] ??= [];
			$courseOptions[CourseOptionsEnum::GENERAL_SETTINGS->value][\Planaday\Config\Course\General\GeneralOptionsEnum::INCLUDE_E_LEARNING_DAY_PARTS->value] =
				$courseOptions[CourseOptionsEnum::OVERVIEW_SETTINGS->value]['INCLUDE_E_LEARNING_DAY_PARTS'];
			unset($courseOptions[CourseOptionsEnum::OVERVIEW_SETTINGS->value]['INCLUDE_E_LEARNING_DAY_PARTS']);
		}

		update_option( $this->pluginData->getFullPrefix() . CourseSettings::getIndex(), $courseOptions );
	}
}