<?php

namespace Planaday\Platform\WordpressConfig\Migrations\Version1;

use Planaday\Config\Booking\BookingOptionsEnum;
use Planaday\Config\Booking\BookingSettings;
use Planaday\Config\Booking\Form\Address\AddressOptionsEnum;
use Planaday\Config\Booking\Form\BookingFormOptionsEnum;
use Planaday\Config\Booking\Form\Company\CompanyOptionsEnum;
use Planaday\Config\Booking\Form\Company\Invoice\InvoiceOptionsEnum;
use Planaday\Config\Booking\Form\Materials\MaterialsOptionsEnum;
use Planaday\Config\Booking\Form\Student\StudentOptionsEnum;
use Planaday\Config\Booking\Submission\BookingSubmissionOptionsEnum;
use Planaday\Config\Booking\Submission\Mail\MailOptionsEnum;
use Planaday\Config\Booking\Submission\Redirecting\RedirectOptionsEnum;
use Planaday\Config\Course\Calendar\CalendarOptionsEnum;
use Planaday\Config\Course\CourseOptionsEnum;
use Planaday\Config\Course\CourseSettings;
use Planaday\Config\Course\Detail\DetailOptionsEnum;
use Planaday\Config\Course\Overview\OverviewOptionsEnum;
use Planaday\Config\Course\Search\SearchOptionsEnum;
use Planaday\Config\General\Api\ApiOptionsEnum;
use Planaday\Config\General\Debug\DebugOptionsEnum;
use Planaday\Config\General\GeneralOptionsEnum;
use Planaday\Config\General\GeneralSettings;
use Planaday\Config\General\Price\PriceOptionsEnum;
use Planaday\Config\Internal\InternalOptionsEnum;
use Planaday\Config\Internal\InternalSettings;
use Planaday\Config\Payment\PaymentOptionsEnum;
use Planaday\Config\Payment\PaymentSettings;
use Planaday\Utility\PluginData;

class MigrateTo1_0_0 {
	public function __construct(
		protected PluginData $pluginData
	) {}

	public function migrate(): void{
		$oldOptions = get_option( 'planaday-api-general', null);

		if(!isset($oldOptions) || !is_array($oldOptions)) {
			update_option( $this->pluginData->getFullPrefix() . '-version', '1.0.0' );
			return;
		}

		$bookingOptions = [
			BookingOptionsEnum::BOOKING_FORM->value => [
				BookingFormOptionsEnum::ADDRESS->value => [
					AddressOptionsEnum::ASK_FOR_NUMBER_EXTENSION->value => $this->getBool( $oldOptions['vraaghuisnrext'] ?? null )
				],

				BookingFormOptionsEnum::BOOKING_FORM_TITLE->value => $this->getString( $oldOptions['teksttitelbooking'] ?? null ),

				BookingFormOptionsEnum::COMPANY->value => [
					CompanyOptionsEnum::ALLOW_COMPANIES->value       => ! $this->getBool( $oldOptions['onlybookingelparticulier'] ?? null ),
					CompanyOptionsEnum::AS_COMPANY_DEFAULT->value    => ! $this->getBool( $oldOptions['voorkeurbooleancompany'] ?? null ),
					CompanyOptionsEnum::ASK_PHONE_NUMBER->value      => $this->getBool( $oldOptions['toonformphonenumbercompany'] ?? null ),
					CompanyOptionsEnum::PHONE_NUMBER_REQUIRED->value => $this->getBool( $oldOptions['toonformphonenumbercompanymanatory'] ?? null ),

					CompanyOptionsEnum::INVOICE->value => [
						InvoiceOptionsEnum::ASK_FOR_ADDRESS->value => $this->getBool( $oldOptions['vraagfinancieleinfobijbedrijf'] ?? null ),
						InvoiceOptionsEnum::ASK_FOR_EMAIL->value   => $this->getBool( $oldOptions['toonemailinvoice'] ?? null ),
						InvoiceOptionsEnum::EMAIL_REQUIRED->value  => $this->getBool( $oldOptions['toonemailinvoicemanatory'] ?? null )
					]
				],

				BookingFormOptionsEnum::MATERIALS->value => [
					MaterialsOptionsEnum::ASK_MATERIALS_BOOKING_FORM->value           => $this->getBool( $oldOptions['materialbookingactive'] ?? null ),
					MaterialsOptionsEnum::MATERIALS_FORM_DESCRIPTION->value           => $this->getString( $oldOptions['materialtext'] ?? null ),
					MaterialsOptionsEnum::MATERIALS_FORM_TITLE->value                 => $this->getString( $oldOptions['materialtitle'] ?? null )
				],

				BookingFormOptionsEnum::STUDENT->value => [
					StudentOptionsEnum::ASK_ADDRESS->value            => $this->getBool( $oldOptions['vraagadrescursist'] ?? null ),
					StudentOptionsEnum::ASK_IF_CONTACT->value         => $this->getBool( $oldOptions['vraagcontactpersoon'] ?? null ),
					StudentOptionsEnum::ASK_NICK_NAME->value          => $this->getBool( $oldOptions['vraagroepnaam'] ?? null ),
					StudentOptionsEnum::ASK_MAIDEN_NAME->value        => $this->getBool( $oldOptions['vraagmeisjesnaam'] ?? null ),
					StudentOptionsEnum::ASK_INTERNAL_REFERENCE->value => $this->getBool( $oldOptions['vraag_internal_reference'] ?? null ),
					StudentOptionsEnum::ASK_COMPANY_POSITION->value   => $this->getBool( $oldOptions['toonformpositionstudent'] ?? null ),
					StudentOptionsEnum::ASK_COST_CENTER_CODE->value   => $this->getBool( $oldOptions['vraagcostcentercode'] ?? null ),
					StudentOptionsEnum::ASK_EMPLOYEE_NUMBER->value    => $this->getBool( $oldOptions['vraagpersoneelsnummer'] ?? null ),
					StudentOptionsEnum::ASK_DATE_OF_BIRTH->value      => $this->getBool( $oldOptions['toonformdateofbirth'] ?? null ),
					StudentOptionsEnum::ASK_PLACE_OF_BIRTH->value     => $this->getBool( $oldOptions['toonformcountryofbirth'] ?? null ),
					StudentOptionsEnum::ASK_PHONE_NUMBER->value       => $this->getBool( $oldOptions['toonformphonenumber'] ?? null ),

					StudentOptionsEnum::ASK_CODE_95->value => $this->getBool( $oldOptions['toonoptiecode95'] ?? null ),
					StudentOptionsEnum::ASK_SOOB->value    => $this->getBool( $oldOptions['toonoptiesoob'] ?? null ),

					StudentOptionsEnum::ASK_REMARK->value => $this->getBool( $oldOptions['toonstudentremark'] ?? null ),

					StudentOptionsEnum::COST_CENTER_CODE_REQUIRED->value => $this->getBool( $oldOptions['vraagcostcentercodemanatory'] ?? null ),
					StudentOptionsEnum::DATE_OF_BIRTH_REQUIRED->value    => $this->getBool( $oldOptions['toonformdateofbirthmanatory'] ?? null ),
					StudentOptionsEnum::PLACE_OF_BIRTH_REQUIRED->value   => $this->getBool( $oldOptions['toonformcountryofbirthmanatory'] ?? null ),
					StudentOptionsEnum::PHONE_NUMBER_REQUIRED->value     => $this->getBool( $oldOptions['toonformphonenumbermanatory'] ?? null ),
					StudentOptionsEnum::COMPANY_POSITION_REQUIRED->value => $this->getBool( $oldOptions['toonformpositionstudentmanatory'] ?? null ),

					StudentOptionsEnum::TERMS_AND_CONDITIONS_REQUIRED->value => $this->getBool( $oldOptions['toonformalgemenevoorwaarden'] ?? null ),
					StudentOptionsEnum::TERMS_AND_CONDITIONS_URL->value      => $this->getString( $oldOptions['urlalgemenevoorwaarden'] ?? null ),

					StudentOptionsEnum::COST_CENTER_CODE_TEXT->value => $this->getString( $oldOptions['tekstkostenplaats'] ?? null ),
					StudentOptionsEnum::CODE_95_TEXT->value          => $this->getString( $oldOptions['tekstcode95optie'] ?? null ),
					StudentOptionsEnum::SOOB_TEXT->value             => $this->getString( $oldOptions['tekstsooboptie'] ?? null )
				],

				BookingFormOptionsEnum::ASK_API_ATTRIBUTES->value => $this->getBool( $oldOptions['toonapiattributen'] ?? null )
			],
			BookingOptionsEnum::SUBMISSION->value   => [
				BookingSubmissionOptionsEnum::MAIL->value => [
					MailOptionsEnum::MAIL_STUDENT->value          => $this->getBool( $oldOptions['mailcursusaanmeldingcursist'] ?? null ),
					MailOptionsEnum::MAIL_COMPANY->value          => $this->getBool( $oldOptions['mailcursusaanmeldingbedrijf'] ?? null ),
					MailOptionsEnum::MAIL_STUDENT_CONTENTS->value => $this->getString( $oldOptions['mailbedankttekst'] ?? null ),
					MailOptionsEnum::MAIL_COMPANY_CONTENTS->value => $this->getString( $oldOptions['mailbedankttekstbedrijf'] ?? null ),
					MailOptionsEnum::MAIL_ADMIN->value            => $this->checkIfEmail( $oldOptions['mailcursusaanmelding'] ?? null ),
					MailOptionsEnum::ADMIN_ADDRESS->value         => $this->getString( $oldOptions['mailcursusaanmelding'] ?? null ),
				],

				BookingSubmissionOptionsEnum::REDIRECT->value => [
					RedirectOptionsEnum::REDIRECT_AFTER_SUCCESS->value   => $this->getBool( $oldOptions['bedanktredirect'] ?? null ),
					RedirectOptionsEnum::REDIRECT_SUCCESS_PAGE->value    => $this->getInt( $oldOptions['bedankurl'] ?? null ),
					RedirectOptionsEnum::NO_REDIRECT_SUCCESS_TEXT->value => $this->getString( $oldOptions['bedankttekst'] ?? null ),

					RedirectOptionsEnum::REDIRECT_AFTER_FAILURE->value   => $this->getBool( $oldOptions['bedanktredirectmislukt'] ?? null ),
					RedirectOptionsEnum::REDIRECT_FAILURE_PAGE->value    => $this->getInt( $oldOptions['bedankurlmislukt'] ?? null ),
					RedirectOptionsEnum::NO_REDIRECT_FAILURE_TEXT->value => $this->getString( $oldOptions['bedankttekstmislukt'] ?? null ),
				]
			]
		];
		update_option( $this->pluginData->getFullPrefix() . BookingSettings::getIndex(), $bookingOptions );

		$courseOptions = [
			CourseOptionsEnum::CALENDAR_SETTINGS->value => [
				CalendarOptionsEnum::BACKGROUND_COLOR->value    => $this->getString( $oldOptions['calendarcolorback'] ?? null ),
				CalendarOptionsEnum::TEXT_COLOR->value          => $this->getString( $oldOptions['calendarcolortext'] ?? null ),
				CalendarOptionsEnum::SHOW_MOUSEOVER_TEXT->value => $this->getBool( $oldOptions['tooncalendarmouseover'] ?? null )
			],

			CourseOptionsEnum::DETAIL_SETTINGS->value => [
				DetailOptionsEnum::SHOW_SOOB_LABEL->value                 => $this->getBool( $oldOptions['toonsoobdetailcursus'] ?? null ),
				DetailOptionsEnum::SHOW_CODE_95_LABEL->value              => $this->getBool( $oldOptions['tooncode95cursus'] ?? null ),
				DetailOptionsEnum::SHOW_LABELS->value                     => $this->getBool( $oldOptions['tooncursuslabelsdetail'] ?? null ),
				DetailOptionsEnum::SHOW_DAY_PART_COUNT->value             => $this->getBool( $oldOptions['toondetaildagdelen'] ?? null ),
				DetailOptionsEnum::SHOW_DAY_PART_LIST->value              => $this->getBool( $oldOptions['toondetaildagdelenlijst'] ?? null ),
				DetailOptionsEnum::SHOW_LOCATION_DAY_PART->value          => $this->getBool( $oldOptions['toonlocatiedagdeel'] ?? null ),
				DetailOptionsEnum::SHOW_E_LEARNING_ICON->value            => $this->getBool( $oldOptions['tooncursuselearning'] ?? null ),
				DetailOptionsEnum::SHOW_E_LEARNING_DAY_PART->value        => $this->getBool( $oldOptions['toonelearningdagdeel'] ?? null ),
				DetailOptionsEnum::SHOW_LEVEL_COURSE->value               => $this->getBool( $oldOptions['toonniveau'] ?? null ),
				DetailOptionsEnum::SHOW_DESCRIPTION_DAY_PART->value       => $this->getBool( $oldOptions['toonomschrijvingdagdeel'] ?? null ),
				DetailOptionsEnum::SHOW_AVAILABILITY->value               => $this->getBool( $oldOptions['toonbeschikbareplaatsen'] ?? null ),
				DetailOptionsEnum::SHOW_START_GUARANTEE_LABEL->value      => $this->getBool( $oldOptions['startgarantiedetail'] ?? null ),
				DetailOptionsEnum::SHOW_MONEY_BACK_LABEL->value           => $this->getBool( $oldOptions['geldterugdetail'] ?? null ),
				DetailOptionsEnum::SHOW_FINANCIAL_INFO->value             => $this->getBool( $oldOptions['tooncostsremark'] ?? null ),
				DetailOptionsEnum::SHOW_PRICE->value                      => $this->getBool( $oldOptions['toonprijsdetailpagina'] ?? null ),
				DetailOptionsEnum::SHOW_PRICE_WITH_AND_WITHOUT_TAX->value => $this->getBool( $oldOptions['detailbothprices'] ?? null ),
				DetailOptionsEnum::SHOW_ICONS->value                      => $this->getBool( $oldOptions['detailshowicons'] ?? null ),
				DetailOptionsEnum::INCLUDE_E_LEARNING_DAY_PARTS->value    => $this->getBool( $oldOptions['countelearningasdaypart'] ?? null ),
				DetailOptionsEnum::SHOW_DESCRIPTION->value                => $this->getBool( $oldOptions['toonomschrijvingcursus'] ?? null ),
				DetailOptionsEnum::SHOW_LABELS_DAY_PART->value            => $this->getBool( $oldOptions['toonlabelindagdeel'] ?? null ),
			],

			CourseOptionsEnum::GENERAL_SETTINGS->value => [
				\Planaday\Config\Course\General\GeneralOptionsEnum::DAY_PART_TEXT->value           => $this->getString( $oldOptions['dagdelentekst'] ?? null ),
				\Planaday\Config\Course\General\GeneralOptionsEnum::INCLUDE_OPTION_IN_COUNT->value => $this->getBool( $oldOptions['optiesmeetellen'] ?? null ),
				\Planaday\Config\Course\General\GeneralOptionsEnum::SKIP_E_LEARNING_ONLY->value    => $this->getBool( $oldOptions['skipcoursewithonlyelearning'] ?? null )
			],

			CourseOptionsEnum::OVERVIEW_SETTINGS->value => [
				OverviewOptionsEnum::SHOW_CODE_95_ICON->value           => $this->getBool( $oldOptions['tooncode95overzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_SOOB_ICON->value              => $this->getBool( $oldOptions['toonsooboverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_E_LEARNING_ICON->value        => $this->getBool( $oldOptions['tooncursuselearning'] ?? null ),
				OverviewOptionsEnum::SHOW_MONEY_BACK_NOTICE->value      => $this->getBool( $oldOptions['geldterugoverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_START_GUARANTEE_NOTICE->value => $this->getBool( $oldOptions['startgarantieoverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_FINANCIAL_INFO->value         => $this->getBool( $oldOptions['tooncostsremarkoverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_PRICE->value                  => $this->getBool( $oldOptions['toonprijs'] ?? null ),
				OverviewOptionsEnum::SHOW_DAY_PART_COUNT->value         => $this->getBool( $oldOptions['toondagdelen'] ?? null ),
				OverviewOptionsEnum::SHOW_LABELS->value                 => $this->getBool( $oldOptions['tooncursuslabelsoverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_FIRST_LOCATION->value         => $this->getBool( $oldOptions['toonlocatiebijoverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_AVAILABILITY->value           => $this->getBool( $oldOptions['toonbeschikbareplaatsen'] ?? null ),

				OverviewOptionsEnum::SHOW_COURSE_BUTTON->value => $this->getBool( $oldOptions['toonbutton'] ?? null ),
				OverviewOptionsEnum::COURSE_BUTTON_TEXT->value => $this->getString( $oldOptions['buttontekstoverzicht'] ?? null ),

				OverviewOptionsEnum::SHOW_DESCRIPTION->value       => isset($oldOptions['tooninblockvorm']) ? ($this->getInt( $oldOptions['limiettekstomschrijving']) !== 0) : null,
				OverviewOptionsEnum::MAX_LENGTH_DESCRIPTION->value => $this->getInt( $oldOptions['limiettekstomschrijving'] ?? null ),

				OverviewOptionsEnum::SHOW_DAY_PART_LIST->value           => $this->getBool( $oldOptions['toondetaildagdelenlijstinoverzicht'] ?? null ),
				'INCLUDE_E_LEARNING_DAY_PARTS'                           => $this->getBool( $oldOptions['countelearningasdaypart'] ?? null ),
				OverviewOptionsEnum::SHOW_LOCATION_DAY_PART->value       => $this->getBool( $oldOptions['toonlocatiedagdeeloverzicht'] ?? null ),
				OverviewOptionsEnum::SHOW_LABELS_DAY_PART->value         => $this->getBool( $oldOptions['toonlabelindagdeel'] ?? null ),

				OverviewOptionsEnum::NO_COURSE_TEXT->value                   => $this->getString( $oldOptions['tekstgeencursussen'] ?? null ),
				OverviewOptionsEnum::INCLUDE_FULL_COURSES->value             => $this->getBool( $oldOptions['toonvollecursus'] ?? null ),
				OverviewOptionsEnum::INCLUDE_PARTIALLY_PASSED_COURSES->value => $this->getBool( $oldOptions['tooncursusdagdelenverleden'] ?? null )
			],

			CourseOptionsEnum::SEARCH_SETTINGS->value => [
				SearchOptionsEnum::ASK_TITLE->value      => $this->getBool( $oldOptions['toontextbijsearch'] ?? null ),
				SearchOptionsEnum::ASK_LOCATION->value   => $this->getBool( $oldOptions['toonlocatiesbijsearch'] ?? null ),
				SearchOptionsEnum::ASK_LABELS->value     => $this->getBool( $oldOptions['toonlabelsbijsearch'] ?? null ),
				SearchOptionsEnum::ASK_CODE_95->value    => $this->getBool( $oldOptions['tooncode95bijsearch'] ?? null ),
				SearchOptionsEnum::ASK_SOOB->value       => $this->getBool( $oldOptions['toonsoobbijsearch'] ?? null ),
				SearchOptionsEnum::ASK_E_LEARNING->value => $this->getBool( $oldOptions['toonelearningbijsearch'] ?? null ),
				SearchOptionsEnum::OUTPUT_FORMAT->value  => isset($oldOptions['tooninblockvorm']) ? ($this->getBool( $oldOptions['tooninblockvorm'] ) !== false ? 0 : 2) : null
			]
		];
		update_option( $this->pluginData->getFullPrefix() . CourseSettings::getIndex(), $courseOptions );

		$generalOptions = [
			GeneralOptionsEnum::API_SETTINGS->value => [
				ApiOptionsEnum::API_KEY->value => $this->getString( $oldOptions['key'] ?? null ),
				ApiOptionsEnum::DOMAIN->value  => $this->getString( $oldOptions['url'] ?? null ),
				ApiOptionsEnum::REFRESH_INTERVAL_COURSES->value   => $this->getInt( $oldOptions['dbcoursehours'] ?? null ),
				ApiOptionsEnum::REFRESH_INTERVAL_DAY_PARTS->value => $this->getInt( $oldOptions['dbdaypartshours'] ?? null ),
				ApiOptionsEnum::REFRESH_INTERVAL_LOCATIONS->value => $this->getInt( $oldOptions['dbdaypartshours'] ?? null )
			],

			GeneralOptionsEnum::DEBUG->value => [
				DebugOptionsEnum::SEND_DEBUG_LOGS->value => null
			],

			GeneralOptionsEnum::PRICE_OPTIONS->value => [
				PriceOptionsEnum::INCLUDING_TAX->value  => !$this->getBool( $oldOptions['btwinofexbtwtonen'] ?? null ),
				PriceOptionsEnum::WITH_TAX_LABEL->value => $this->getBool( $oldOptions['btwinofexbtwtonenlabel'] ?? null ),
			]
		];
		update_option( $this->pluginData->getFullPrefix() . GeneralSettings::getIndex(), $generalOptions );

		$oldPaymentOptions = get_option( 'planaday-api-payment' );
		$paymentOptions = [
			PaymentOptionsEnum::PAYMENT_NOTICE->value => $this->getString( $oldPaymentOptions['toelichting'] ?? null ),
			PaymentOptionsEnum::PAYMENT_ACTIVE->value => $this->getBool( $oldOptions['betalingenactief'] ?? null ),
			PaymentOptionsEnum::CANCEL_BOOKING_IF_NO_PAYMENT->value => $this->getBool( $oldPaymentOptions['cancelbookingafternopayment'] ?? null ),
			PaymentOptionsEnum::TEST_PAYMENT_ACTIVE->value => $this->getBool( $oldPaymentOptions['idealtestmodus'] ?? null )
		];
		update_option( $this->pluginData->getFullPrefix() . PaymentSettings::getIndex(), $paymentOptions );

		$oldCss = get_option('planaday-api-css');
		$internalOptions = [
			InternalOptionsEnum::GLOBAL_CSS->value => $this->getString( $oldCss['sccss-content'] )
		];
		update_option( $this->pluginData->getFullPrefix() . InternalSettings::getIndex(), $internalOptions );

		update_option( $this->pluginData->getFullPrefix() . '-version', '1.0.0' );
	}

	protected function getBool($toBeTested):?bool {
		if ($toBeTested === '' || $toBeTested === null) return null;
		return $toBeTested === "1" ||
		       strtolower((string)$toBeTested) === "ja" ||
		       $toBeTested === 1 ||
		       $toBeTested === true;
	}

	protected function getInt($toBeConverted):?int {
		if ( $toBeConverted == "" || !filter_var($toBeConverted, FILTER_VALIDATE_INT)) return null;

		return (int)$toBeConverted;
	}

	protected function getString($toBeConverted):?string {
		if ($toBeConverted == "") return null;

		return "" . $toBeConverted;
	}

	protected function checkIfEmail($toBeChecked):bool {
		return (is_string($toBeChecked) && filter_var($toBeChecked, FILTER_VALIDATE_EMAIL));
	}
}