<?php

namespace CommerceBird;

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

if ( ! class_exists( 'CMBIRD_AI_Product_Blocks_Display' ) ) {
	/**
	 * Displays AI product blocks on classic WooCommerce templates.
	 */
	class CMBIRD_AI_Product_Blocks_Display {

		const OPTION_ENABLED             = 'cmbird_ai_review_summary_enabled';
		const OPTION_DYNAMIC_FAQ_ENABLED = 'cmbird_ai_content_writer_enabled';
		const META_DYNAMIC_FAQ_KEY       = '_cmbird_ai_dynamic_faq';
		const AJAX_ACTION_AI_QA          = 'cmbird_ai_product_qa';
		const HONEYPOT_TRANSIENT_PREFIX  = 'cmbird_ai_qa_hp_';
		const HONEYPOT_MIN_SECONDS       = 2;
		const HONEYPOT_MAX_SECONDS       = 3600;

		/**
		 * Constructor.
		 */
		public function __construct() {
			add_action( 'woocommerce_product_meta_end', array( $this, 'render' ), 20 );
			add_filter( 'woocommerce_product_tabs', array( $this, 'register_dynamic_faq_tab' ), 30 );
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_q_and_a_assets' ) );
			add_action( 'wp_ajax_' . self::AJAX_ACTION_AI_QA, array( $this, 'handle_ai_q_and_a' ) );
			add_action( 'wp_ajax_nopriv_' . self::AJAX_ACTION_AI_QA, array( $this, 'handle_ai_q_and_a' ) );
		}

		/**
		 * Enqueue AI Q&A frontend script on product detail pages only.
		 *
		 * @return void
		 */
		public function enqueue_q_and_a_assets(): void {
			if ( ! function_exists( 'is_product' ) || ! \is_product() ) {
				return;
			}

			if ( ! (bool) get_option( self::OPTION_DYNAMIC_FAQ_ENABLED, false ) ) {
				return;
			}

			wp_enqueue_script(
				'cmbird-ai-qa-chat',
				CMBIRD_URL . 'admin/js/cmbird-ai-qa-chat.js',
				array(),
				CMBIRD_VERSION,
				true
			);

			wp_localize_script(
				'cmbird-ai-qa-chat',
				'cmbirdAiQaConfig',
				array(
					'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
					'action'   => self::AJAX_ACTION_AI_QA,
					'messages' => array(
						'enterQuestion' => __( 'Please enter a question first.', 'commercebird' ),
						'answerError'   => __( 'Unable to answer this question right now.', 'commercebird' ),
						'qLabel'        => __( 'Q:', 'commercebird' ),
						'aLabel'        => __( 'A:', 'commercebird' ),
					),
				)
			);
		}

		/**
		 * Register Dynamic FAQ tab on single product pages.
		 *
		 * @param array $tabs Existing WooCommerce tabs.
		 * @return array
		 */
		public function register_dynamic_faq_tab( array $tabs ): array {
			if ( ! function_exists( 'is_product' ) || ! \is_product() ) {
				return $tabs;
			}

			if ( ! (bool) get_option( self::OPTION_DYNAMIC_FAQ_ENABLED, false ) ) {
				return $tabs;
			}

			$tabs['cmbird_dynamic_faq'] = array(
				'title'    => __( 'Dynamic FAQ', 'commercebird' ),
				'priority' => 55,
				'callback' => array( $this, 'render_dynamic_faq_tab' ),
			);

			return $tabs;
		}

		/**
		 * Render Dynamic FAQ tab content.
		 *
		 * @return void
		 */
		public function render_dynamic_faq_tab(): void {
			global $product;

			if ( ! $product || ! method_exists( $product, 'get_id' ) ) {
				echo '<p>' . esc_html__( 'Dynamic FAQ is not available for this product.', 'commercebird' ) . '</p>';
				return;
			}

			$product_id   = (int) $product->get_id();
			$faq_content  = (string) get_post_meta( $product_id, self::META_DYNAMIC_FAQ_KEY, true );
			$review_notes = (string) get_post_meta( $product_id, \CommerceBird\CMBIRD_AI_Product_Blocks_Generator::META_KEY, true );
			$generator    = new \CommerceBird\CMBIRD_AI_Product_Blocks_Generator();
			$history      = $generator->get_existing_q_and_a( $product_id );

			$this->render_q_and_a_chatbox( $product_id, $history );

			if ( '' !== trim( $faq_content ) ) {
				echo wp_kses_post( wpautop( $faq_content ) );
				return;
			}

			echo '<p>' . esc_html__( 'Dynamic FAQ is enabled and will appear here once enough product feedback is available.', 'commercebird' ) . '</p>';

			if ( '' !== trim( $review_notes ) ) {
				echo '<p><strong>' . esc_html__( 'Latest AI Product Insight:', 'commercebird' ) . '</strong></p>';
				echo '<p>' . esc_html( $review_notes ) . '</p>';
			}
		}

		/**
		 * Render AI Q&A chat interface.
		 *
		 * @param int   $product_id Product ID.
		 * @param array $history Existing Q&A history.
		 * @return void
		 */
		private function render_q_and_a_chatbox( int $product_id, array $history ): void {
			$nonce        = wp_create_nonce( self::AJAX_ACTION_AI_QA . '_' . $product_id );
			$honeypot     = $this->create_honeypot_payload( $product_id );
			$field_a_name = $honeypot['field_a_name'];
			$field_b_name = $honeypot['field_b_name'];

			echo '<div class="cmbird-ai-qa-box" style="border:1px solid #e2e8f0;border-radius:10px;padding:14px;margin-bottom:16px;background:#f8fafc;">';
			echo '<h3 style="margin:0 0 6px;font-size:16px;">' . esc_html__( 'AI Q&A Block', 'commercebird' ) . '</h3>';
			echo '<p style="margin:0 0 12px;color:#475569;font-size:13px;">' . esc_html__( 'Ask a question about this product. Answers are generated from product details, reviews, and previous Q&A.', 'commercebird' ) . '</p>';
			echo '<div class="cmbird-ai-qa-history" style="display:flex;flex-direction:column;gap:8px;margin-bottom:12px;">';

			if ( ! empty( $history ) ) {
				foreach ( $history as $item ) {
					if ( empty( $item['question'] ) || empty( $item['answer'] ) ) {
						continue;
					}
					echo '<details class="cmbird-ai-qa-item" style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:0 10px;">';
					echo '<summary style="padding:9px 0;cursor:pointer;color:#0f172a;"><strong>' . esc_html__( 'Q:', 'commercebird' ) . '</strong> ' . esc_html( (string) $item['question'] ) . '</summary>';
					echo '<div style="padding:0 0 10px;color:#334155;">';
					echo '<p style="margin:0;"><strong>' . esc_html__( 'A:', 'commercebird' ) . '</strong> ' . esc_html( (string) $item['answer'] ) . '</p>';
					echo '</div>';
					echo '</details>';
				}
			} else {
				echo '<p class="cmbird-ai-qa-empty" style="margin:0;color:#64748b;font-size:12px;">' . esc_html__( 'No visitor Q&A yet. Ask the first question below.', 'commercebird' ) . '</p>';
			}

			echo '</div>';
			echo '<div style="display:flex;gap:8px;align-items:flex-start;">';
			echo '<div style="display:none !important;">';
			echo '<label for="' . esc_attr( $field_a_name ) . '">' . esc_html__( 'Website', 'commercebird' ) . '</label>';
			echo '<input type="text" class="cmbird-ai-qa-hp-a" id="' . esc_attr( $field_a_name ) . '" name="' . esc_attr( $field_a_name ) . '" value="" autocomplete="off" tabindex="-1">';
			echo '<label for="' . esc_attr( $field_b_name ) . '">' . esc_html__( 'Confirm email', 'commercebird' ) . '</label>';
			echo '<input type="text" class="cmbird-ai-qa-hp-b" id="' . esc_attr( $field_b_name ) . '" name="' . esc_attr( $field_b_name ) . '" value="" autocomplete="off" tabindex="-1">';
			echo '</div>';
			echo '<textarea class="cmbird-ai-qa-input" id="cmbird-ai-qa-question-' . esc_attr( (string) $product_id ) . '" name="cmbird_ai_qa_question" rows="2" style="flex:1;border:1px solid #cbd5e1;border-radius:8px;padding:9px;resize:vertical;" placeholder="' . esc_attr__( 'e.g. Is this waterproof and suitable for outdoor use?', 'commercebird' ) . '"></textarea>';
			echo '<button type="button" class="button wp-element-button button-primary cmbird-ai-qa-submit" data-product-id="' . esc_attr( (string) $product_id ) . '" data-nonce="' . esc_attr( $nonce ) . '" data-hp-session="' . esc_attr( $honeypot['session_key'] ) . '" data-hp-token="' . esc_attr( $honeypot['token'] ) . '" data-hp-created="' . esc_attr( (string) $honeypot['created_at'] ) . '" data-hp-field-a-name="' . esc_attr( $field_a_name ) . '" data-hp-field-b-name="' . esc_attr( $field_b_name ) . '">' . esc_html__( 'Ask AI', 'commercebird' ) . '</button>';
			echo '</div>';
			echo '<p class="cmbird-ai-qa-feedback" style="display:none;margin:8px 0 0;color:#b91c1c;"></p>';
			echo '</div>';
		}

		/**
		 * Handle frontend AI Q&A requests.
		 *
		 * @return void
		 */
		public function handle_ai_q_and_a(): void {
			$product_id = isset( $_POST['product_id'] ) ? absint( wp_unslash( $_POST['product_id'] ) ) : 0;
			$nonce      = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			$question   = isset( $_POST['question'] ) ? sanitize_textarea_field( wp_unslash( $_POST['question'] ) ) : '';

			if ( $product_id <= 0 || '' === $question ) {
				wp_send_json_error( array( 'message' => __( 'Invalid product or question.', 'commercebird' ) ), 400 );
			}

			if ( ! wp_verify_nonce( $nonce, self::AJAX_ACTION_AI_QA . '_' . $product_id ) ) {
				wp_send_json_error( array( 'message' => __( 'Security check failed.', 'commercebird' ) ), 403 );
			}

			$field_a_name = isset( $_POST['hp_field_a_name'] ) ? sanitize_key( wp_unslash( $_POST['hp_field_a_name'] ) ) : '';
			$field_b_name = isset( $_POST['hp_field_b_name'] ) ? sanitize_key( wp_unslash( $_POST['hp_field_b_name'] ) ) : '';

			$honeypot_request = array(
				'session_key'   => isset( $_POST['hp_session'] ) ? sanitize_text_field( wp_unslash( $_POST['hp_session'] ) ) : '',
				'token'         => isset( $_POST['hp_token'] ) ? sanitize_text_field( wp_unslash( $_POST['hp_token'] ) ) : '',
				'created_at'    => isset( $_POST['hp_created'] ) ? absint( wp_unslash( $_POST['hp_created'] ) ) : 0,
				'field_a_name'  => $field_a_name,
				'field_b_name'  => $field_b_name,
				'field_a_value' => ( '' !== $field_a_name && isset( $_POST[ $field_a_name ] ) ) ? sanitize_text_field( wp_unslash( $_POST[ $field_a_name ] ) ) : '',
				'field_b_value' => ( '' !== $field_b_name && isset( $_POST[ $field_b_name ] ) ) ? sanitize_text_field( wp_unslash( $_POST[ $field_b_name ] ) ) : '',
			);

			if ( ! $this->validate_honeypot_request( $product_id, $honeypot_request ) ) {
				wp_send_json_error( array( 'message' => __( 'Spam protection triggered. Please refresh and try again.', 'commercebird' ) ), 429 );
			}

			if ( ! (bool) get_option( self::OPTION_DYNAMIC_FAQ_ENABLED, false ) ) {
				wp_send_json_error( array( 'message' => __( 'Dynamic FAQ is currently disabled.', 'commercebird' ) ), 403 );
			}

			$generator = new \CommerceBird\CMBIRD_AI_Product_Blocks_Generator();
			$answer    = $generator->answer_question( $product_id, $question );

			if ( '' === $answer ) {
				$message = $generator->get_last_error_message();
				if ( '' === $message ) {
					$message = __( 'Unable to answer this question right now.', 'commercebird' );
				}
				wp_send_json_error( array( 'message' => $message ), 500 );
			}

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

		/**
		 * Create honeypot payload and persist validation record.
		 *
		 * @param int $product_id Product ID.
		 * @return array
		 */
		private function create_honeypot_payload( int $product_id ): array {
			$session_key = wp_generate_uuid4();
			$created_at  = time();
			$field_a     = 'website_confirm_' . wp_rand( 1000, 9999 );
			$field_b     = 'email_verify_' . wp_rand( 1000, 9999 );
			$user_agent  = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
			$ua_hash     = md5( $user_agent );
			$token       = wp_hash( $session_key . '|' . $product_id . '|' . $created_at . '|' . $field_a . '|' . $field_b . '|' . $ua_hash, 'nonce' );

			$payload = array(
				'session_key'  => $session_key,
				'created_at'   => $created_at,
				'product_id'   => $product_id,
				'field_a_name' => $field_a,
				'field_b_name' => $field_b,
				'ua_hash'      => $ua_hash,
				'token'        => $token,
			);

			set_transient( self::HONEYPOT_TRANSIENT_PREFIX . $session_key, $payload, self::HONEYPOT_MAX_SECONDS );

			return $payload;
		}

		/**
		 * Validate honeypot payload from AJAX request.
		 *
		 * @param int   $product_id Product ID.
		 * @param array $request Honeypot request payload.
		 * @return bool
		 */
		private function validate_honeypot_request( int $product_id, array $request ): bool {
			$session_key = (string) ( $request['session_key'] ?? '' );
			$token       = (string) ( $request['token'] ?? '' );
			$created_at  = absint( $request['created_at'] ?? 0 );
			$field_a     = (string) ( $request['field_a_name'] ?? '' );
			$field_b     = (string) ( $request['field_b_name'] ?? '' );

			if ( '' === $session_key || '' === $token || 0 === $created_at || '' === $field_a || '' === $field_b ) {
				return false;
			}

			$stored = get_transient( self::HONEYPOT_TRANSIENT_PREFIX . $session_key );
			if ( ! is_array( $stored ) ) {
				return false;
			}

			$user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
			$ua_hash    = md5( $user_agent );
			if ( empty( $stored['ua_hash'] ) || ! hash_equals( (string) $stored['ua_hash'], $ua_hash ) ) {
				return false;
			}

			if ( (int) $stored['product_id'] !== $product_id ) {
				return false;
			}

			if ( (string) $stored['field_a_name'] !== $field_a || (string) $stored['field_b_name'] !== $field_b ) {
				return false;
			}

			if ( (int) $stored['created_at'] !== $created_at ) {
				return false;
			}

			if ( ! hash_equals( (string) $stored['token'], $token ) ) {
				return false;
			}

			$elapsed = time() - $created_at;
			if ( $elapsed < self::HONEYPOT_MIN_SECONDS || $elapsed > self::HONEYPOT_MAX_SECONDS ) {
				return false;
			}

			$field_a_value = (string) ( $request['field_a_value'] ?? '' );
			$field_b_value = (string) ( $request['field_b_value'] ?? '' );

			if ( '' !== $field_a_value || '' !== $field_b_value ) {
				return false;
			}

			return true;
		}

		/**
		 * Render summary block.
		 *
		 * @return void
		 */
		public function render(): void {
			if ( ! (bool) get_option( self::OPTION_ENABLED, false ) ) {
				return;
			}

			global $product;
			if ( ! $product || ! method_exists( $product, 'get_id' ) ) {
				return;
			}

			$product_id = (int) $product->get_id();
			$summary    = get_post_meta( $product_id, \CommerceBird\CMBIRD_AI_Product_Blocks_Generator::META_KEY, true );
			$updated    = (int) get_post_meta( $product_id, \CommerceBird\CMBIRD_AI_Product_Blocks_Generator::META_UPDATED_KEY, true );

			if ( empty( $summary ) ) {
				return;
			}

			echo '<div class="cmbird-ai-review-summary">';
			echo '<h3>' . esc_html__( 'Review Summary', 'commercebird' ) . '</h3>';
			echo '<p>' . esc_html( $summary ) . '</p>';
			if ( $updated > 0 ) {
				echo '<small>';
				echo esc_html(
					sprintf(
						/* translators: %s: human readable timestamp. */
						__( 'AI-generated summary based on recent reviews · Updated %s ago', 'commercebird' ),
						human_time_diff( $updated, time() )
					)
				);
				echo '</small>';
			}
			echo '</div>';
		}
	}
}

if ( ! class_exists( 'CMBIRD_AI_Review_Summary_Display' ) && class_exists( 'CMBIRD_AI_Product_Blocks_Display' ) ) {
	class_alias( __NAMESPACE__ . '\\CMBIRD_AI_Product_Blocks_Display', __NAMESPACE__ . '\\CMBIRD_AI_Review_Summary_Display' );
}
