<?php

class SettingsPage extends PageBase {

	const PAGE_NAME = "ai2media_settings_page";

	// options name
	const API_OPTIONS_GROUP = "ai2media_api_options_group";
	const TOKEN_OPTION_NAME = "ai2media_token_option";
	const WS_OPTION_NAME = "ai2media_ws_option";

	const API_SECTION_NAME = "api_settings_section";

	static function get_shared(): SettingsPage {
		return parent::get_shared();
	}

	function ai2media_settings_init() {
		$this->api_settings_init();
	}

	function show() {
		?>
        <h2><?php echo __("Settings", "a2m") ;?></h2>
        <form action="options.php" method="post">
			<?php
			settings_fields( self::API_OPTIONS_GROUP );
			do_settings_sections( self::PAGE_NAME );
			submit_button( __("Save", "a2m") );
			?>
        </form>
		<?php
	}


////  Api settings  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	private function api_settings_init() {
		register_setting( self::API_OPTIONS_GROUP, self::TOKEN_OPTION_NAME );
		register_setting( self::API_OPTIONS_GROUP, self::WS_OPTION_NAME );

		add_settings_section(
			self::API_SECTION_NAME,
			'API',
			[ $this, 'display_section_description' ],
			self::PAGE_NAME
		);

		$this->add_api_setting_field( "token_setting_field", __("User token", "a2m"), "display_token_field" );
		$this->add_api_setting_field( "ws_setting_field", "Рабочее пространство", "display_ws_field" );
	}

	function display_section_description() {
        _e("To correctly import content from the Ai2Media website, enter the user token and specify the workspace ID", "a2m");
	}

	function display_token_field() {
		$token_value = get_option( self::TOKEN_OPTION_NAME );
		?>
        <input type="text" class="api-settings" id="token_field" name="<?php echo esc_attr( self::TOKEN_OPTION_NAME ); ?>"
               value="<?php echo esc_attr( $token_value ); ?>"
               placeholder="<?php _e("Token", "a2m")?>"/>
		<?php
	}

	function display_ws_field() {
		?>
        <select id="ws_select_field" class="blinking api-settings" disabled name="<?php echo esc_attr( self::WS_OPTION_NAME ); ?>">
            <option selectedl>Загрузка...</option>
        </select>
		<?php
	}

	function get_workspaces_callback() {
		$token = $_POST['token'];
		$workspaces = Ai2MediaService::get_workspaces($token);

		if ($workspaces) {
			wp_send_json_success($workspaces);
		} else {
			wp_send_json_error('Failed to fetch workspaces');
		}
	}
	private function add_api_setting_field( $id, string $title, $callback ) {
		add_settings_field(
			$id,
			$title,
			[ $this, $callback ],
			self::PAGE_NAME,
			self::API_SECTION_NAME
		);
	}

}


add_action('wp_ajax_get_workspaces', [SettingsPage::get_shared(), 'get_workspaces_callback']);
