<?php
/**
 * Plugin settings page.
 *
 * @package Effortless_Taiwan_Mandarin_Helper
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Registers and renders the Settings → Mandarin Helper page and handles cache clearing.
 */
class ELTMH_Settings {

	/**
	 * Sets up the instance.
	 *
	 * @param ELTMH_Cache $cache Cache instance used by the clear-cache action.
	 */
	public function __construct( private ELTMH_Cache $cache ) {}

	/** Registers all hooks. */
	public function init(): void {
		add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_post_eltmh_clear_cache', array( $this, 'handle_clear_cache' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_settings_assets' ) );
		add_action( 'wp_ajax_eltmh_test_key', array( $this, 'handle_test_key' ) );
	}

	/**
	 * Enqueues the inline JS for the test-key button on the settings page only.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_settings_assets( string $hook ): void {
		if ( 'settings_page_eltmh-settings' !== $hook ) {
			return;
		}

		wp_register_script( 'eltmh-settings', false, array(), ELTMH_VERSION, true );
		wp_enqueue_script( 'eltmh-settings' );
		wp_localize_script(
			'eltmh-settings',
			'eltmhSettings',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'eltmh_test_key' ),
			)
		);
		wp_add_inline_script( 'eltmh-settings', $this->test_key_inline_js() );
		wp_add_inline_script( 'eltmh-settings', $this->provider_toggle_inline_js() );
	}

	/**
	 * Returns the inline JS for the test-connection buttons.
	 *
	 * @return string
	 */
	private function test_key_inline_js(): string {
		return <<<'JS'
( function () {
    'use strict';
    document.querySelectorAll( '.eltmh-test-key' ).forEach( function ( btn ) {
        btn.addEventListener( 'click', function () {
            var provider = btn.dataset.provider;
            var keyInput = document.getElementById( 'eltmh-' + provider + '-api-key' );
            var statusEl = document.getElementById( 'eltmh-test-status-' + provider );
            if ( ! keyInput || ! statusEl ) { return; }
            var key = keyInput.value.trim();
            if ( ! key ) {
                statusEl.textContent = 'Please enter an API key first.';
                statusEl.style.color = '#c00';
                return;
            }
            btn.disabled         = true;
            statusEl.textContent = 'Testing…';
            statusEl.style.color = '#666';
            var data = new FormData();
            data.append( 'action', 'eltmh_test_key' );
            data.append( 'nonce', eltmhSettings.nonce );
            data.append( 'provider', provider );
            data.append( 'api_key', key );
            fetch( eltmhSettings.ajaxUrl, { method: 'POST', body: data } )
                .then( function ( r ) { return r.json(); } )
                .then( function ( resp ) {
                    btn.disabled = false;
                    if ( resp.success ) {
                        statusEl.textContent = '✓ Connected';
                        statusEl.style.color = '#0a0';
                    } else {
                        statusEl.textContent = '✗ Error: ' + ( resp.data || 'Unknown error' );
                        statusEl.style.color = '#c00';
                    }
                } )
                .catch( function () {
                    btn.disabled         = false;
                    statusEl.textContent = '✗ Request failed';
                    statusEl.style.color = '#c00';
                } );
        } );
    } );
}() );
JS;
	}

	/**
	 * Returns the inline JS that shows/hides the OpenAI/Anthropic fields and the
	 * AI-Client help text based on the selected provider.
	 *
	 * @return string
	 */
	private function provider_toggle_inline_js(): string {
		return <<<'JS'
( function () {
    'use strict';
    var select = document.getElementById( 'eltmh-provider-select' );
    var help   = document.getElementById( 'eltmh-wp-ai-client-help' );
    if ( ! select ) { return; }

    function apply() {
        var isAiClient = 'wp_ai_client' === select.value;
        [ 'openai', 'anthropic' ].forEach( function ( provider ) {
            document.querySelectorAll( '.eltmh-provider-field-' + provider ).forEach( function ( el ) {
                var row = el.closest( 'tr' );
                if ( row ) { row.style.display = isAiClient ? 'none' : ''; }
            } );
        } );
        if ( help ) { help.style.display = isAiClient ? '' : 'none'; }
    }

    select.addEventListener( 'change', apply );
    apply();
}() );
JS;
	}

	/** Adds the Settings → Mandarin Helper page. */
	public function add_settings_page(): void {
		add_options_page(
			__( 'Mandarin Helper Settings', 'effortless-taiwan-mandarin-helper' ),
			__( 'Mandarin Helper', 'effortless-taiwan-mandarin-helper' ),
			'manage_options',
			'eltmh-settings',
			array( $this, 'render_settings_page' )
		);
	}

	/** Registers the eltmh_settings option and its fields. */
	public function register_settings(): void {
		register_setting(
			'eltmh_settings_group',
			'eltmh_settings',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_settings' ),
			)
		);

		add_settings_section( 'eltmh_main', '', '__return_false', 'eltmh-settings' );

		$fields = array(
			'provider'          => __( 'AI Provider', 'effortless-taiwan-mandarin-helper' ),
			'openai_api_key'    => __( 'OpenAI API Key', 'effortless-taiwan-mandarin-helper' ),
			'openai_model'      => __( 'OpenAI Model', 'effortless-taiwan-mandarin-helper' ),
			'anthropic_api_key' => __( 'Anthropic API Key', 'effortless-taiwan-mandarin-helper' ),
			'anthropic_model'   => __( 'Anthropic Model', 'effortless-taiwan-mandarin-helper' ),
		);

		foreach ( $fields as $id => $label ) {
			add_settings_field(
				'eltmh_' . $id,
				$label,
				array( $this, 'render_field_' . $id ),
				'eltmh-settings',
				'eltmh_main'
			);
		}

		add_settings_section(
			'eltmh_display',
			__( 'Display', 'effortless-taiwan-mandarin-helper' ),
			'__return_false',
			'eltmh-settings'
		);

		$display_fields = array(
			'show_original'    => __( 'Show Original', 'effortless-taiwan-mandarin-helper' ),
			'show_chinese'     => __( 'Show Chinese', 'effortless-taiwan-mandarin-helper' ),
			'show_pinyin'      => __( 'Show Pinyin', 'effortless-taiwan-mandarin-helper' ),
			'show_zhuyin'      => __( 'Show Bopomofo', 'effortless-taiwan-mandarin-helper' ),
			'show_translation' => __( 'Show English Translation', 'effortless-taiwan-mandarin-helper' ),
		);

		foreach ( $display_fields as $id => $label ) {
			add_settings_field(
				'eltmh_' . $id,
				$label,
				array( $this, 'render_field_' . $id ),
				'eltmh-settings',
				'eltmh_display'
			);
		}
	}

	/**
	 * Renders a single "Show X" checkbox field shared by all display-toggle settings.
	 *
	 * @param string $id Settings key, e.g. 'show_pinyin'.
	 */
	private function render_display_checkbox( string $id ): void {
		$settings = (array) get_option( 'eltmh_settings', array() );
		$checked  = $settings[ $id ] ?? true;
		?>
		<label>
			<input type="checkbox" name="eltmh_settings[<?php echo esc_attr( $id ); ?>]" value="1" <?php checked( $checked ); ?>>
			<?php esc_html_e( 'Shown by default; can still be overridden per-shortcode.', 'effortless-taiwan-mandarin-helper' ); ?>
		</label>
		<?php
	}

	/** Renders the Show Original checkbox. */
	public function render_field_show_original(): void {
		$this->render_display_checkbox( 'show_original' );
	}

	/** Renders the Show Chinese checkbox. */
	public function render_field_show_chinese(): void {
		$this->render_display_checkbox( 'show_chinese' );
	}

	/** Renders the Show Pinyin checkbox. */
	public function render_field_show_pinyin(): void {
		$this->render_display_checkbox( 'show_pinyin' );
	}

	/** Renders the Show Bopomofo checkbox. */
	public function render_field_show_zhuyin(): void {
		$this->render_display_checkbox( 'show_zhuyin' );
	}

	/** Renders the Show English Translation checkbox. */
	public function render_field_show_translation(): void {
		$this->render_display_checkbox( 'show_translation' );
	}

	/**
	 * Sanitises submitted settings.
	 *
	 * @param mixed $input Raw POST data.
	 * @return array<string,string>
	 */
	public function sanitize_settings( $input ): array {
		$clean = array();

		$clean['provider'] = in_array( $input['provider'] ?? '', array( 'openai', 'anthropic', 'wp_ai_client' ), true )
			? $input['provider']
			: 'openai';

		$clean['openai_api_key']    = sanitize_text_field( $input['openai_api_key'] ?? '' );
		$clean['anthropic_api_key'] = sanitize_text_field( $input['anthropic_api_key'] ?? '' );

		$allowed_openai        = array( 'gpt-4o', 'gpt-4o-mini' );
		$clean['openai_model'] = in_array( $input['openai_model'] ?? '', $allowed_openai, true )
			? $input['openai_model']
			: 'gpt-4o';

		$allowed_anthropic        = array( 'claude-sonnet-4-6', 'claude-haiku-4-5' );
		$clean['anthropic_model'] = in_array( $input['anthropic_model'] ?? '', $allowed_anthropic, true )
			? $input['anthropic_model']
			: 'claude-sonnet-4-6';

		foreach ( array( 'show_original', 'show_chinese', 'show_pinyin', 'show_zhuyin', 'show_translation' ) as $key ) {
			$clean[ $key ] = ! empty( $input[ $key ] );
		}

		return $clean;
	}

	/** Renders the full settings page. */
	public function render_settings_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$cleared = isset( $_GET['eltmh_cleared'] ) ? (int) $_GET['eltmh_cleared'] : -1; // phpcs:ignore WordPress.Security.NonceVerification
		?>
		<div class="wrap">
			<h1><?php echo esc_html( get_admin_page_title() ); ?> <small><?php echo esc_html( ELTMH_VERSION ); ?></small></h1>

			<?php if ( $cleared >= 0 ) : ?>
				<div class="notice notice-success is-dismissible">
					<p>
					<?php
					echo esc_html(
						sprintf(
							/* translators: %d: number of cached entries removed */
							_n(
								'%d cached translation removed.',
								'%d cached translations removed.',
								$cleared,
								'effortless-taiwan-mandarin-helper'
							),
							$cleared
						)
					);
					?>
					</p>
				</div>
			<?php endif; ?>

			<form method="post" action="options.php">
				<?php
				settings_fields( 'eltmh_settings_group' );
				do_settings_sections( 'eltmh-settings' );
				submit_button();
				?>
			</form>

			<hr>
			<h2><?php esc_html_e( 'Cache', 'effortless-taiwan-mandarin-helper' ); ?></h2>
			<p><?php esc_html_e( 'Translations are cached indefinitely. Use this button to clear all cached results.', 'effortless-taiwan-mandarin-helper' ); ?></p>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="eltmh_clear_cache">
				<?php wp_nonce_field( 'eltmh_clear_cache' ); ?>
				<?php submit_button( __( 'Clear All Cached Translations', 'effortless-taiwan-mandarin-helper' ), 'secondary' ); ?>
			</form>
		</div>
		<?php
	}

	/** Renders the Provider dropdown field. */
	public function render_field_provider(): void {
		$settings = (array) get_option( 'eltmh_settings', array() );
		$current  = $settings['provider'] ?? 'openai';
		?>
		<select name="eltmh_settings[provider]" id="eltmh-provider-select">
			<option value="openai" <?php selected( $current, 'openai' ); ?>><?php esc_html_e( 'OpenAI (default)', 'effortless-taiwan-mandarin-helper' ); ?></option>
			<option value="anthropic" <?php selected( $current, 'anthropic' ); ?>><?php esc_html_e( 'Anthropic', 'effortless-taiwan-mandarin-helper' ); ?></option>
			<option value="wp_ai_client" <?php selected( $current, 'wp_ai_client' ); ?>><?php esc_html_e( 'WordPress AI Client (site-configured)', 'effortless-taiwan-mandarin-helper' ); ?></option>
		</select>
		<p id="eltmh-wp-ai-client-help" style="display:none;">
			<?php esc_html_e( "This site's AI provider is configured under Settings; this plugin does not manage or transmit its own API key for this option.", 'effortless-taiwan-mandarin-helper' ); ?>
		</p>
		<?php
	}

	/** Renders the OpenAI API Key field. */
	public function render_field_openai_api_key(): void {
		$settings = (array) get_option( 'eltmh_settings', array() );
		?>
		<div class="eltmh-provider-field-openai">
			<input type="password" id="eltmh-openai-api-key" name="eltmh_settings[openai_api_key]"
				value="<?php echo esc_attr( $settings['openai_api_key'] ?? '' ); ?>"
				class="regular-text">
			<button type="button" class="button eltmh-test-key" data-provider="openai">
				<?php esc_html_e( 'Test connection', 'effortless-taiwan-mandarin-helper' ); ?>
			</button>
			<span id="eltmh-test-status-openai" style="margin-left:0.5em;"></span>
		</div>
		<?php
	}

	/** Renders the OpenAI Model dropdown. */
	public function render_field_openai_model(): void {
		$settings = (array) get_option( 'eltmh_settings', array() );
		$current  = $settings['openai_model'] ?? 'gpt-4o';
		$models   = array( 'gpt-4o', 'gpt-4o-mini' );
		?>
		<div class="eltmh-provider-field-openai">
			<select name="eltmh_settings[openai_model]">
				<?php foreach ( $models as $model ) : ?>
				<option value="<?php echo esc_attr( $model ); ?>" <?php selected( $current, $model ); ?>><?php echo esc_html( $model ); ?></option>
				<?php endforeach; ?>
			</select>
		</div>
		<?php
	}

	/** Renders the Anthropic API Key field. */
	public function render_field_anthropic_api_key(): void {
		$settings = (array) get_option( 'eltmh_settings', array() );
		?>
		<div class="eltmh-provider-field-anthropic">
			<input type="password" id="eltmh-anthropic-api-key" name="eltmh_settings[anthropic_api_key]"
				value="<?php echo esc_attr( $settings['anthropic_api_key'] ?? '' ); ?>"
				class="regular-text">
			<button type="button" class="button eltmh-test-key" data-provider="anthropic">
				<?php esc_html_e( 'Test connection', 'effortless-taiwan-mandarin-helper' ); ?>
			</button>
			<span id="eltmh-test-status-anthropic" style="margin-left:0.5em;"></span>
		</div>
		<?php
	}

	/** Renders the Anthropic Model dropdown. */
	public function render_field_anthropic_model(): void {
		$settings = (array) get_option( 'eltmh_settings', array() );
		$current  = $settings['anthropic_model'] ?? 'claude-sonnet-4-6';
		$models   = array( 'claude-sonnet-4-6', 'claude-haiku-4-5' );
		?>
		<div class="eltmh-provider-field-anthropic">
			<select name="eltmh_settings[anthropic_model]">
				<?php foreach ( $models as $model ) : ?>
				<option value="<?php echo esc_attr( $model ); ?>" <?php selected( $current, $model ); ?>><?php echo esc_html( $model ); ?></option>
				<?php endforeach; ?>
			</select>
		</div>
		<?php
	}

	/**
	 * AJAX handler: tests whether a provider API key is valid.
	 * Calls a cheap endpoint (OpenAI: list models; Anthropic: 1-token message).
	 * Responds with wp_send_json_success() or wp_send_json_error( $message ).
	 */
	public function handle_test_key(): void {
		check_ajax_referer( 'eltmh_test_key', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'Permission denied.', 'effortless-taiwan-mandarin-helper' ) );
			return;
		}

		$provider = sanitize_text_field( wp_unslash( $_POST['provider'] ?? '' ) );
		$api_key  = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );

		if ( empty( $api_key ) ) {
			wp_send_json_error( __( 'No API key provided.', 'effortless-taiwan-mandarin-helper' ) );
			return;
		}

		if ( ! in_array( $provider, array( 'openai', 'anthropic' ), true ) ) {
			wp_send_json_error( __( 'Unknown provider.', 'effortless-taiwan-mandarin-helper' ) );
			return;
		}

		if ( 'anthropic' === $provider ) {
			$response = wp_remote_post(
				'https://api.anthropic.com/v1/messages',
				array(
					'headers' => array(
						'x-api-key'         => $api_key,
						'anthropic-version' => '2023-06-01',
						'Content-Type'      => 'application/json',
					),
					'body'    => wp_json_encode(
						array(
							'model'      => 'claude-haiku-4-5',
							'max_tokens' => 1,
							'messages'   => array(
								array(
									'role'    => 'user',
									'content' => 'Hi',
								),
							),
						)
					),
					'timeout' => 15,
				)
			);
		} else {
			$response = wp_remote_get(
				'https://api.openai.com/v1/models',
				array(
					'headers' => array( 'Authorization' => 'Bearer ' . $api_key ),
					'timeout' => 15,
				)
			);
		}

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( $response->get_error_message() );
			return;
		}

		$status = (int) wp_remote_retrieve_response_code( $response );

		if ( 200 === $status ) {
			wp_send_json_success();
		}

		$body    = json_decode( wp_remote_retrieve_body( $response ), true );
		$message = $body['error']['message'] ?? sprintf(
			/* translators: %d: HTTP status code */
			__( 'HTTP %d', 'effortless-taiwan-mandarin-helper' ),
			$status
		);
		wp_send_json_error( $message );
	}

	/** Handles the clear-cache POST action. */
	public function handle_clear_cache(): void {
		check_admin_referer( 'eltmh_clear_cache' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'effortless-taiwan-mandarin-helper' ) );
		}

		$count = $this->cache->flush_all();

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'          => 'eltmh-settings',
					'eltmh_cleared' => $count,
				),
				admin_url( 'options-general.php' )
			)
		);
		exit;
	}
}
