<?php

namespace Simplyin\Simplyin_W_Plugin\Sync;

class Switch_Info {


	private function get_simplyin_register_by_default(): bool {
		$is_checked_in_shop = get_option( 'simplyin_register_by_default', false );

		if ( is_string( $is_checked_in_shop ) && 'on' === $is_checked_in_shop ) {
			return true;
		}

		return false;

	}

	private function update_simplyin_register_by_default( bool $state ) {
		if ( true === $state ) {
			simplyin()->update_option( 'simplyin_register_by_default',
				'on',
				'sync' );
		} else {
			simplyin()->update_option( 'simplyin_register_by_default',
				'off',
				'sync' );
		}
	}

	private function get_simplyin_register_by_default_backup(): bool {
		$is_checked_in_shop_old = get_option( 'SimplyInRegisterByDefaultStateOld',
			false );

		if ( is_string( $is_checked_in_shop_old ) && 'on' === $is_checked_in_shop_old ) {
			return true;
		}

		return false;

	}

	private function is_switch_deactivated(): bool {
		$disabled = get_option( 'SimplyInRegisterByDefaultDisabled',
			false );

		if ( $disabled ) {
			return true;
		}

		return false;
	}


	private function update_simplyin_register_by_default_backup( bool $state
	) {
		if ( true === $state ) {
			simplyin()->update_option( 'SimplyInRegisterByDefaultStateOld',
				'on',
				'sync' );
		} else {
			simplyin()->update_option( 'SimplyInRegisterByDefaultStateOld',
				'',
				'sync' );
		}
	}

	private function deactivate_switch() {
		simplyin()->update_option( 'SimplyInRegisterByDefaultDisabled',
			true,
			'sync' );

	}

	private function activate_switch() {
		simplyin()->update_option( 'SimplyInRegisterByDefaultDisabled',
			false,
			'sync' );
	}

	public function handle(
		bool $is_checked_from_api,
		string $last_change
	) {

		simplyin()->update_option( 'SimplyInSwitchLastChange',
			$response->switchInfo->lastChange,
			'sync' );


	}


	public function handle_simplyin_register_by_default_state(
		bool $is_checked_from_api
	) {
		$is_checked_in_shop                  = $this->get_simplyin_register_by_default();
		$simplyin_register_by_default_state_old       = $this->get_simplyin_register_by_default_backup();
		$simplyin_register_by_default_disabled_by_api = $this->is_switch_deactivated();


		if ( $simplyin_register_by_default_disabled_by_api ) {
			if ( $is_checked_from_api ) {
				//revert old merchant setting
				$this->update_simplyin_register_by_default( $simplyin_register_by_default_state_old );
				$this->activate_switch();
			}

			return;
		}

		if ( true === $is_checked_from_api && false === $is_checked_in_shop ) {
			//unchecked by merchant
			return;
		}

		if ( false === $is_checked_from_api ) {
			//disable button in admin and switch of
			$this->update_simplyin_register_by_default_backup( $is_checked_in_shop ); //backup merchant setting
			$this->update_simplyin_register_by_default( false );
			$this->deactivate_switch();
		}

	}
}
