<?php
/**
 * AI Assistant Settings Page.
 *
 * Where the API key for the AI features is entered, the model chosen, and the
 * connection tested. Key is stored encrypted via Core\LlmSettings.
 *
 * @package Platform\Helm\Modules\Ai
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Ai;

use Platform\Helm\Core\Authorization;
use Platform\Helm\Core\LlmClient;
use Platform\Helm\Core\LlmSettings;

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

final class AiSettingsPage {

	public const PAGE_SLUG   = 'platform-helm-ai';
	public const PARENT_SLUG = 'platform-helm';
	private const NONCE      = 'platform_helm_ai_settings';
	private const TEST_NONCE = 'platform_helm_ai_test';

	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_menu' ], 48 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
		add_action( 'admin_post_platform_helm_ai_save', [ $this, 'handle_save' ] );
		add_action( 'wp_ajax_platform_helm_ai_test', [ $this, 'ajax_test' ] );
	}

	/**
	 * This screen's markup uses the shared SEO-reports component set (.ph-gsc),
	 * so it needs gsc.css in addition to the global Helm admin.css. Loaded only on
	 * this page.
	 */
	public function enqueue( string $hook ): void {
		unset( $hook );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( (string) $_GET['page'] ) ) : '';
		if ( self::PAGE_SLUG !== $page ) {
			return;
		}
		wp_enqueue_style(
			'platform-helm-gsc',
			PLATFORM_HELM_URL . 'assets/css/gsc.css',
			[],
			PLATFORM_HELM_VERSION
		);
	}

	public function register_menu(): void {
		if ( ! Authorization::is_master_admin() ) {
			return;
		}
		add_submenu_page(
			self::PARENT_SLUG,
			__( 'AI Assistant', 'platform-helm' ),
			__( 'AI Assistant', 'platform-helm' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
	}

	public function handle_save(): void {
		if ( ! Authorization::is_master_admin() ) {
			wp_die( esc_html__( 'Not allowed.', 'platform-helm' ), '', [ 'response' => 403 ] );
		}
		check_admin_referer( self::NONCE );
		LlmSettings::save(
			sanitize_text_field( wp_unslash( $_POST['base_url'] ?? '' ) ),
			sanitize_text_field( wp_unslash( $_POST['model'] ?? '' ) ),
			isset( $_POST['api_key'] ) ? trim( (string) wp_unslash( $_POST['api_key'] ) ) : '' // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
		);
		wp_safe_redirect( add_query_arg( [ 'page' => self::PAGE_SLUG, 'saved' => 1 ], admin_url( 'admin.php' ) ) );
		exit;
	}

	public function ajax_test(): void {
		check_ajax_referer( self::TEST_NONCE, 'nonce' );
		Authorization::require_master_admin_ajax();
		$res = LlmClient::chat(
			[
				[ 'role' => 'user', 'content' => 'Reply with the single word: OK' ],
			],
			[ 'max_tokens' => 5, 'temperature' => 0 ]
		);
		if ( is_wp_error( $res ) ) {
			wp_send_json_error( [ 'message' => $res->get_error_message() ] );
		}
		wp_send_json_success( [ 'message' => __( 'Connected — the AI responded.', 'platform-helm' ) ] );
	}

	public function render(): void {
		Authorization::require_master_admin();
		$configured = LlmSettings::is_configured();
		?>
		<div class="wrap ph-gsc">
			<h1><?php esc_html_e( 'AI Assistant', 'platform-helm' ); ?></h1>
			<p class="ph-gsc-lead"><?php esc_html_e( 'Connect an OpenAI-compatible AI API to power the refined-intro rewriter (and more to come). Groq is recommended — it is free, fast, and does not train on your data. Calls only happen when you click an AI button in the admin; never on the public site.', 'platform-helm' ); ?></p>

			<?php if ( isset( $_GET['saved'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<div class="notice notice-success inline"><p><?php esc_html_e( 'Settings saved.', 'platform-helm' ); ?></p></div>
			<?php endif; ?>

			<div class="ph-gsc-card">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<?php wp_nonce_field( self::NONCE ); ?>
					<input type="hidden" name="action" value="platform_helm_ai_save" />
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><label for="ph-ai-key"><?php esc_html_e( 'API key', 'platform-helm' ); ?></label></th>
							<td>
								<input type="password" id="ph-ai-key" name="api_key" class="regular-text" autocomplete="off" placeholder="<?php echo $configured ? esc_attr__( '•••••••• (saved — leave blank to keep)', 'platform-helm' ) : 'gsk_…'; ?>" />
								<p class="description"><?php esc_html_e( 'Get a free key at console.groq.com. Stored encrypted.', 'platform-helm' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="ph-ai-base"><?php esc_html_e( 'API base URL', 'platform-helm' ); ?></label></th>
							<td><input type="text" id="ph-ai-base" name="base_url" class="regular-text" value="<?php echo esc_attr( LlmSettings::base_url() ); ?>" />
								<p class="description"><?php esc_html_e( 'Groq: https://api.groq.com/openai/v1 · Cerebras/OpenRouter also work (OpenAI-compatible).', 'platform-helm' ); ?></p></td>
						</tr>
						<tr>
							<th scope="row"><label for="ph-ai-model"><?php esc_html_e( 'Model', 'platform-helm' ); ?></label></th>
							<td><input type="text" id="ph-ai-model" name="model" class="regular-text" value="<?php echo esc_attr( LlmSettings::model() ); ?>" />
								<p class="description"><?php esc_html_e( 'Groq default: llama-3.3-70b-versatile.', 'platform-helm' ); ?></p></td>
						</tr>
					</table>
					<p>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Save settings', 'platform-helm' ); ?></button>
						<button type="button" class="button" id="ph-ai-test" <?php disabled( ! $configured ); ?>><?php esc_html_e( 'Test connection', 'platform-helm' ); ?></button>
						<span id="ph-ai-test-msg" class="ph-gsc-msg" aria-live="polite"></span>
					</p>
				</form>
			</div>

			<script>
			( function () {
				var btn = document.getElementById( 'ph-ai-test' );
				var msg = document.getElementById( 'ph-ai-test-msg' );
				if ( ! btn ) { return; }
				btn.addEventListener( 'click', function () {
					btn.disabled = true;
					msg.textContent = <?php echo wp_json_encode( esc_html__( 'Testing…', 'platform-helm' ) ); ?>;
					var body = new URLSearchParams();
					body.append( 'action', 'platform_helm_ai_test' );
					body.append( 'nonce', <?php echo wp_json_encode( wp_create_nonce( self::TEST_NONCE ) ); ?> );
					fetch( <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>, { method: 'POST', credentials: 'same-origin', body: body } )
						.then( function ( r ) { return r.json(); } )
						.then( function ( res ) {
							msg.textContent = ( res && res.data && res.data.message ) ? res.data.message : 'Done.';
							msg.style.color = ( res && res.success ) ? '#1a7f37' : '#b32d2e';
							btn.disabled = false;
						} )
						.catch( function () { msg.textContent = 'Test failed.'; msg.style.color = '#b32d2e'; btn.disabled = false; } );
				} );
			}() );
			</script>
		</div>
		<?php
	}
}
