<?php
/**
 * Optional OpenAI-powered setup troubleshooting (merchant API key).
 *
 * @package SHC4WC
 */

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

class SHC4WC_AI_Assistant {
	const OPENAI_CHAT_URL = 'https://api.openai.com/v1/chat/completions';

	/** @var self|null */
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function has_api_key() {
		$key = self::get_api_key();
		return '' !== $key;
	}

	public static function get_api_key() {
		$settings = SHC4WC_Plugin::get_settings();
		return isset( $settings['ai_openai_api_key'] ) ? trim( (string) $settings['ai_openai_api_key'] ) : '';
	}

	private function __construct() {
		add_action( 'wp_ajax_shc4wc_ai_troubleshoot', array( $this, 'ajax_troubleshoot' ) );
	}

	/**
	 * @param string $oauth_status Optional shc4wc_status query value.
	 */
	public static function render_onboarding_panel( $oauth_status = '' ) {
		$has_key = self::has_api_key();
		$status  = class_exists( 'SHC4WC_REST_API' ) ? SHC4WC_REST_API::build_status_payload() : array();
		?>
		<div class="shc4wc-onboarding-ai-panel">
			<h2><?php esc_html_e( 'AI setup assistant (optional)', 'payments-connect-square' ); ?></h2>
			<p class="description">
				<?php esc_html_e( 'Describe your setup problem. If you saved an OpenAI API key under Payments Square Connect → connection settings, the assistant suggests fixes. Card data and Square tokens are never sent.', 'payments-connect-square' ); ?>
			</p>
			<ul class="shc4wc-onboarding-ai-status">
				<li>
					<?php
					echo esc_html(
						! empty( $status['square_connected'] )
							? __( 'Square: connected', 'payments-connect-square' )
							: __( 'Square: not connected', 'payments-connect-square' )
					);
					?>
				</li>
				<li>
					<?php
					echo esc_html(
						! empty( $status['gateway_enabled'] )
							? __( 'WooCommerce gateway: enabled', 'payments-connect-square' )
							: __( 'WooCommerce gateway: disabled', 'payments-connect-square' )
					);
					?>
				</li>
				<li>
					<?php
					echo esc_html(
						$has_key
							? __( 'OpenAI key: saved', 'payments-connect-square' )
							: __( 'OpenAI key: not set (add under connection settings)', 'payments-connect-square' )
					);
					?>
				</li>
			</ul>
			<?php if ( '' !== (string) $oauth_status ) : ?>
				<p class="description">
					<?php
					printf(
						/* translators: %s: OAuth status code from URL. */
						esc_html__( 'Last connection status code: %s', 'payments-connect-square' ),
						esc_html( (string) $oauth_status )
					);
					?>
				</p>
			<?php endif; ?>
			<p>
				<label for="shc4wc-ai-question" class="screen-reader-text"><?php esc_html_e( 'Describe your issue', 'payments-connect-square' ); ?></label>
				<textarea id="shc4wc-ai-question" class="large-text" rows="3" placeholder="<?php esc_attr_e( 'Example: Connect Square fails with oauth_claim_failed after redirect…', 'payments-connect-square' ); ?>"></textarea>
			</p>
			<p>
				<button type="button" class="button button-secondary shc4wc-ai-troubleshoot-btn" <?php echo $has_key ? '' : ' disabled="disabled"'; ?>>
					<?php esc_html_e( 'Get AI help', 'payments-connect-square' ); ?>
				</button>
				<?php if ( ! $has_key ) : ?>
					<a class="button" href="<?php echo esc_url( SHC4WC_Connection_Settings::page_url() ); ?>"><?php esc_html_e( 'Add OpenAI API key', 'payments-connect-square' ); ?></a>
				<?php endif; ?>
			</p>
			<div class="shc4wc-onboarding-ai-response" aria-live="polite" hidden></div>
		</div>
		<?php
	}

	public function ajax_troubleshoot() {
		check_ajax_referer( 'shc4wc_ai_troubleshoot', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized', 'payments-connect-square' ) ), 403 );
		}

		$question = isset( $_POST['question'] ) ? sanitize_textarea_field( wp_unslash( $_POST['question'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
		if ( '' === trim( $question ) ) {
			wp_send_json_error( array( 'message' => __( 'Please describe your issue.', 'payments-connect-square' ) ), 400 );
		}

		if ( ! self::has_api_key() ) {
			wp_send_json_error(
				array(
					'message' => __( 'Add your OpenAI API key under Payments Square Connect → connection settings first.', 'payments-connect-square' ),
				),
				400
			);
		}

		$oauth_status = isset( $_POST['oauth_status'] ) ? sanitize_text_field( wp_unslash( $_POST['oauth_status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
		$answer       = $this->ask_openai( $question, $oauth_status );

		if ( is_wp_error( $answer ) ) {
			wp_send_json_error( array( 'message' => $answer->get_error_message() ), 500 );
		}

		wp_send_json_success( array( 'answer' => $answer ) );
	}

	/**
	 * @param string $question     Merchant question.
	 * @param string $oauth_status Optional status from URL.
	 * @return string|WP_Error
	 */
	private function ask_openai( $question, $oauth_status = '' ) {
		$context = $this->build_safe_context( $oauth_status );
		/**
		 * Filter safe context sent to the AI assistant (no secrets).
		 *
		 * @param array<string, mixed> $context  Safe diagnostic context.
		 * @param string               $question Merchant question.
		 */
		$context = apply_filters( 'shc4wc_ai_troubleshoot_context', $context, $question );

		$system = 'You are a helpful WordPress and WooCommerce plugin support assistant for Payments Square Connect (Square Hosted Checkout). '
			. 'Give short, numbered troubleshooting steps. Never ask for or handle card numbers, CVV, or Square OAuth tokens. '
			. 'Prefer Sandbox for testing. Mention wp_mail, webhooks, and location selection when relevant.';

		$user = "Plugin context (JSON):\n" . wp_json_encode( $context ) . "\n\nMerchant question:\n" . $question;

		$response = wp_remote_post(
			self::OPENAI_CHAT_URL,
			array(
				'timeout' => 45,
				'headers' => array(
					'Authorization' => 'Bearer ' . self::get_api_key(),
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'model'       => 'gpt-4o-mini',
						'temperature' => 0.3,
						'messages'    => array(
							array(
								'role'    => 'system',
								'content' => $system,
							),
							array(
								'role'    => 'user',
								'content' => $user,
							),
						),
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		$body = json_decode( (string) wp_remote_retrieve_body( $response ), true );

		if ( $code < 200 || $code >= 300 ) {
			$message = __( 'OpenAI request failed. Check your API key and account credits.', 'payments-connect-square' );
			if ( is_array( $body ) && ! empty( $body['error']['message'] ) ) {
				$message = sanitize_text_field( (string) $body['error']['message'] );
			}
			return new WP_Error( 'shc4wc_openai_failed', $message );
		}

		$content = '';
		if ( is_array( $body ) && ! empty( $body['choices'][0]['message']['content'] ) ) {
			$content = trim( (string) $body['choices'][0]['message']['content'] );
		}

		if ( '' === $content ) {
			return new WP_Error( 'shc4wc_openai_empty', __( 'Empty response from OpenAI.', 'payments-connect-square' ) );
		}

		return wp_kses_post( $content );
	}

	/**
	 * @param string $oauth_status OAuth status query arg.
	 * @return array<string, mixed>
	 */
	private function build_safe_context( $oauth_status = '' ) {
		$diag = SHC4WC_Plugin::get_admin_diagnostics();

		$context = array(
			'status'       => class_exists( 'SHC4WC_REST_API' ) ? SHC4WC_REST_API::build_status_payload() : array(),
			'oauth_status' => sanitize_text_field( (string) $oauth_status ),
			'site_url'     => home_url( '/' ),
			'php_version'  => PHP_VERSION,
			'wp_version'   => get_bloginfo( 'version' ),
		);

		if ( is_array( $diag ) && ! empty( $diag ) ) {
			$context['last_diagnostic'] = array(
				'context' => isset( $diag['context'] ) ? (string) $diag['context'] : '',
				'worker_error' => isset( $diag['worker_error'] ) ? (string) $diag['worker_error'] : '',
				'transport_error' => isset( $diag['transport_error'] ) ? (string) $diag['transport_error'] : '',
				'http_code' => isset( $diag['http_code'] ) ? (int) $diag['http_code'] : 0,
			);
		}

		return $context;
	}
}
