<?php
/**
 * Shortcode to display a product box.
 *
 * Generates a product box based on a given product ID.
 * Includes title, image, price, Prime status, rating, product details,
 * and various shop links.
 *
 * @package Boxyfy
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Haupt-Shortcode-Callback: [boxyfy_produktbox id="123"]
 *
 * @param array $atts Shortcode-Attribute.
 * @return string     HTML-Ausgabe der Produktbox.
 */
function boxyfy_shortcode_box( $atts ) {

	/* ─────────────────────────
	 * 1) Attribute verarbeiten
	 * ───────────────────────── */
	$atts = shortcode_atts(
		array(
			'id'                    => null,
			'product_tag_simple'    => '',
			'product_tag_simple2'   => '',
			'product_tag_linktext'  => '',
			'product_tag_link'      => '',
			'product_tag_link_rel'  => 'dofollow',
			'product_tag_linktext2' => '',
			'product_tag_link2'     => '',
			'product_tag_link2_rel' => 'dofollow',
			'show_productinfo'      => 'yes',
			'productinfo_limit'     => '5',
		),
		$atts
	);

	$post_id = (int) $atts['id'];
	if ( ! $post_id ) {
		return '<p>' . esc_html__( 'Kein gültiges Produkt angegeben.', 'boxyfy' ) . '</p>';
	}

	/* ─────────────────────────
	 * 2) Produkt-Grunddaten
	 * ───────────────────────── */
	$asin          = get_post_meta( $post_id, 'tsprodukt_asin_price', true );
	$preis_save    = get_post_meta( $post_id, 'tsprodukt_saving_basis', true ); // UVP.
	$price         = get_post_meta( $post_id, 'tsprodukt_price1', true );       // Amazon-Preis.
	$price_display = ! empty( $price ) ? esc_html( $price ) : 0;

	$prime_status = get_post_meta( $post_id, 'tsprodukt_prime_status', true ); // Prime-Flag.

	/* Ersparnis in % berechnen */
	$percent_savings = 0;
	if ( $price_display > 0 && ! empty( $preis_save ) && floatval( $preis_save ) > 0 ) {
		$percent_savings = 100 - ( ( $price_display / floatval( $preis_save ) ) * 100 );
	}

	/* ─────────────────────────
	 * 3) Optionen laden
	 * ───────────────────────── */
	$box_header_font_size           = get_option( 'boxyfy_box_header_font_size', 21 );
	$box_header_fontweights         = (int) get_option( 'boxyfy_box_header_fontweights', 600 );
	$box_info_font_size             = get_option( 'boxyfy_box_info_font_size', 16 );
	$box_title_color                = get_option( 'boxyfy_box_farbe_title', '#004e75' );
	$box_info_text_color            = get_option( 'boxyfy_box_info_text_color', '#000000' );
	$box_shop_button_background     = get_option( 'boxyfy_box_shop_button_background', '#0173ab' );
	$box_bewertung_text_background  = get_option( 'boxyfy_box_bewertung_text', '#07338c' );
	$box_shop_button_text           = get_option( 'boxyfy_box_shop_button_text', 'zum Shop' );
	$box_tsproduktlabel             = get_option( 'boxyfy_box_tsproduktlabel', '#0173ab' );

	/* Bewertungsskalen */
	$bewertung  = get_post_meta( $post_id, '_tsprodukt_bewertung', true );
	$green_min  = get_option( 'boxyfy_green_rating_min', 80 );
	$green_max  = get_option( 'boxyfy_green_rating_max', 100 );
	$yellow_min = get_option( 'boxyfy_yellow_rating_min', 55 );
	$yellow_max = get_option( 'boxyfy_yellow_rating_max', 79 );
	$red_min    = get_option( 'boxyfy_red_rating_min', 0 );
	$red_max    = get_option( 'boxyfy_red_rating_max', 54 );

	/* Sales-Rank */
	$sales_rank = get_post_meta( $post_id, 'tsprodukt_sales_rank', true );

	/* Amazon-Partner-URL */
	$options      = get_option(
		'boxyfy_amazon_settings',
		array(
			'access_key'  => '',
			'secret_key'  => '',
			'partner_tag' => '',
			'host'        => 'webservices.amazon.de',
			'region'      => 'eu-west-1',
		)
	);
	$partner_tag  = $options['partner_tag'];
	$purchase_url = 'https://www.amazon.de/dp/' . esc_attr( $asin ) . '?tag=' . esc_attr( $partner_tag ) . '&linkCode=ogi&th=1';

	/* Produktbild */
	$product_image = get_the_post_thumbnail( $post_id, array( 230, 230 ) );

	/* ─────────────────────────
	 * 4) Produkt-Infos (Tabellen-Liste)
	 * ───────────────────────── */
	$produkt_info    = get_post_meta( $post_id, 'tsprodukt_info', true );
	$produkt_details = '';
	if ( ! empty( $produkt_info ) ) {
		$limit = (int) $atts['productinfo_limit'];
		$count = 0;
		foreach ( $produkt_info as $info ) {
			if ( $count >= $limit ) {
				break;
			}
			$produkt_details .= '<li><strong>' . esc_html( $info['name'] ) . ':</strong> '
				. esc_html( $info['value'] ) . ' ' . esc_html( $info['unit'] ) . '</li>';
			$count ++;
		}
	}

	/* ─────────────────────────
	 * 5) Tags / Badges
	 * ───────────────────────── */
	$tags_html = '<div class="tsprodukt-box-tags">';
	if ( $atts['product_tag_simple'] ) {
		$tags_html .= '<span class="tag">' . esc_html( $atts['product_tag_simple'] ) . '</span>';
	}
	if ( $atts['product_tag_simple2'] ) {
		$tags_html .= '<span class="tag">' . esc_html( $atts['product_tag_simple2'] ) . '</span>';
	}
	if ( $atts['product_tag_linktext'] && $atts['product_tag_link'] ) {
		$icon_url  = plugins_url( 'assets/images/link-icon.svg', BOXYFY_PLUGIN_FILE );
		$tags_html .= '<a href="' . esc_url( $atts['product_tag_link'] ) . '" class="tag tag-link" rel="' . esc_attr( $atts['product_tag_link_rel'] ) . '">
				<img src="' . esc_url( $icon_url ) . '" alt="' . esc_attr__( 'Einzelne Amazon Produktboxen', 'boxyfy' ) . '"> '
				. esc_html( $atts['product_tag_linktext'] ) . '</a>';
	}
	if ( $atts['product_tag_linktext2'] && $atts['product_tag_link2'] ) {
		$icon_url  = plugins_url( 'assets/images/link-icon.svg', BOXYFY_PLUGIN_FILE );
		$tags_html .= '<a href="' . esc_url( $atts['product_tag_link2'] ) . '" class="tag tag-link" rel="' . esc_attr( $atts['product_tag_link2_rel'] ) . '">
				<img src="' . esc_url( $icon_url ) . '" alt="' . esc_attr__( 'Einzelne Amazon Produktboxen', 'boxyfy' ) . '"> '
				. esc_html( $atts['product_tag_linktext2'] ) . '</a>';
	}
	$tags_html .= '</div>';

	/* ─────────────────────────
	 * 6) Bewertung (Note & Farbe)
	 * ───────────────────────── */
	if ( $bewertung ) {
		if ( $bewertung >= $green_min && $bewertung <= $green_max ) {
			$bewertung_style = 'bewertung-green';
		} elseif ( $bewertung >= $yellow_min && $bewertung <= $yellow_max ) {
			$bewertung_style = 'bewertung-yellow';
		} elseif ( $bewertung >= $red_min && $bewertung <= $red_max ) {
			$bewertung_style = 'bewertung-red';
		} else {
			$bewertung_style = 'bewertung-default';
		}
		$bewertung_html = '<span class="tsprodukt-bewertung-label-box">' . esc_html__( 'Bewertung', 'boxyfy' ) . '</span>'
			. '<span class="' . esc_attr( $bewertung_style ) . '">' . esc_html( $bewertung ) . '</span>';
	} else {
		$bewertung_html = '<span class="tsprodukt-bewertung-label-box">' . esc_html__( 'Noch keine Bewertung vorhanden.', 'boxyfy' ) . '</span>';
	}

	/* ─────────────────────────
	 * 7) Sterne-Bewertung
	 * ───────────────────────── */
	$tsproduct_top_starrating   = get_post_meta( $post_id, 'tsprodukte_star_rating', true );
	$star_block                 = '';
	if ( $tsproduct_top_starrating ) {
		$full_stars  = floor( $tsproduct_top_starrating );
		$half_star   = ( $tsproduct_top_starrating - $full_stars ) >= 0.5 ? 1 : 0;
		$empty_stars = 5 - $full_stars - $half_star;

		$star_block  = '<div class="boxyfy-rating-container"><div class="boxyfy-rating-stars-shortcode">';
		for ( $i = 0; $i < $full_stars; $i ++ ) {
			$star_block .= '<i class="fas fa-star"></i>';
		}
		if ( $half_star ) {
			$star_block .= '<i class="fas fa-star-half-alt"></i>';
		}
		for ( $i = 0; $i < $empty_stars; $i ++ ) {
			$star_block .= '<i class="far fa-star"></i>';
		}
		$star_block .= '</div><span class="boxyfy-rating-value">' . esc_html( $tsproduct_top_starrating ) . ' / 5</span></div>';
	}

	/* ─────────────────────────
	 * 8) Box-Grundgerüst
	 * ───────────────────────── */
	$output  = '<div class="tsprodukt-box">';
	$output .= '	<div class="tsprodukt-box-image">';
	$output .=		( $product_image ? $product_image : '<p>' . esc_html__( 'Kein Bild verfügbar', 'boxyfy' ) . '</p>' );
	$output .=		$star_block;
	$output .= '	</div>';

	$output .= '	<div class="tsprodukt-box-content">';
	$output .= '		<div class="tsprodukt-box-header"><a href="' . esc_url( get_permalink( $post_id ) ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . get_the_title( $post_id ) . '</a></div>';

	$output .= '		<div class="tsprodukt-box-bewertung">' . $bewertung_html;
	if ( $sales_rank ) {
	$output .= '		<span class="tsprodukt-bewertung-verkaufsrang-box boxyfy-salesrank-tooltip" data-tooltip="' . esc_attr__( 'Der Verkaufsrang auf Amazon zeigt die Beliebtheit eines Produkts innerhalb einer Kategorie an. Je niedriger der Rang, desto häufiger wird das Produkt verkauft.', 'boxyfy' ) . '">' . esc_html__( 'Verkaufsrang:', 'boxyfy' ) . ' <strong>' . sprintf( esc_html__( 'Platz %s', 'boxyfy' ), esc_html( $sales_rank ) ) . '</strong></span>';
	}
	$output .= '		</div>';

	$output .=		$tags_html;

	$show_chatbox = ( 'yes' === get_option( 'boxyfy_show_ki_chatbox_singleproductbox', 'no' ) );

		if ( $show_chatbox ) {
	
		$output .= '<details class="boxyfy-singleproduct-ai-accordion">
			
			<summary class="boxyfy-singleproduct-ai-summary">
				<img src="' . esc_url( plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/images/ai-chat.png' ) . '" 
			     	alt="' . esc_attr__( 'KI‑Chat Icon', 'boxyfy' ) . '" 
			    >
				' . esc_html__( 'KI-Berater bei Produktfragen', 'boxyfy' ) . '
			</summary>

			<div class="boxyfy-singleproduct-ai-chatbox">
			<span class="boxyfy-singleproduct-ai-headline">' .
				esc_html__( 'Stell der KI jetzt Deine Fragen, z.B. zum Produkt selbst oder zu anderen Produkten.', 'boxyfy' ) .
			'</span>

			<button id="boxyfy-singleproduct-ai-generate-questions" class="boxyfy-singleproduct-ai-button">'
				. esc_html__( 'Beispiel‑Fragen zum Produkt generieren', 'boxyfy' ) .
			'</button>

			<div id="boxyfy-singleproduct-ai-suggested-questions" class="boxyfy-singleproduct-ai-suggestions"></div>

			<textarea id="boxyfy-singleproduct-aichat-question"
			          class="boxyfy-singleproduct-ai-textarea"
			          rows="4"
			          placeholder="' . esc_attr__( 'z. B.: Wie laut ist der [Produktname …] im Betrieb?', 'boxyfy' ) . '"></textarea>

			<button id="boxyfy-singleproduct-aichat-submit" class="boxyfy-singleproduct-ai-submit">'
				. esc_html__( 'Frage stellen', 'boxyfy' ) .
			'</button>

			<p class="boxyfy-singleproduct-ai-info1">' .
				esc_html__( 'Info: KI mit Live-Websuche für aktuelle Antworten.', 'boxyfy' ) .
			'</p>
			
			<p class="boxyfy-singleproduct-ai-info2">' .
				esc_html__( 'Tipp: Gib den Produktnamen mit an, damit die Antwort präziser ist.', 'boxyfy' ) .
			'</p>

			<div id="boxyfy-singleproduct-aichat-response" class="boxyfy-singleproduct-ai-response"></div>

			<p class="boxyfy-singleproduct-aichat-disclaimer"><strong>' .
				esc_html__( 'Hinweis:', 'boxyfy' ) .
			'</strong> ' .
				esc_html__( 'Diese Chatbox nutzt den externen KI-Dienst Perplexity.ai. Dabei werden Daten an dessen Server übermittelt. Weitere Informationen findest Du in der Datenschutzerklärung dieser Website.', 'boxyfy' ) .
			'</p>
		</div>
	</details>';
}

	if ( 'no' !== strtolower( $atts['show_productinfo'] ) ) {
		$output .= '<div class="tsprodukt-box-info"><ul>' . $produkt_details . '</ul></div>';
	}

	/* ─────────────────────────
	 * 9) Preis-Sektion aufbauen
	 * ───────────────────────── */
	$all_prices = array();

	if ( $price_display > 0 ) {
		$all_prices[] = array(
			'shop'                     => 'Amazon',
			'preis'                    => $price_display,
			'prime_status'             => $prime_status,
			'versandkosten_kostenfrei' => '',
			'inkl_versandkosten'       => '',
			'zzgl_versandkosten'       => '',
			'link'                     => $purchase_url,
		);
	}

	$zusatz_preise = get_post_meta( $post_id, 'boxyfy_weitere_preise', true );
	if ( ! empty( $zusatz_preise ) && is_array( $zusatz_preise ) ) {
		foreach ( $zusatz_preise as $zp ) {
			if ( ! empty( $zp['shop'] ) && ! empty( $zp['preis'] ) ) {
				$all_prices[] = array(
					'shop'                     => $zp['shop'],
					'preis'                    => $zp['preis'],
					'prime_status'             => '',
					'versandkosten_kostenfrei' => $zp['versandkosten_kostenfrei'] ?? '',
					'inkl_versandkosten'       => $zp['inkl_versandkosten'] ?? '',
					'zzgl_versandkosten'       => $zp['zzgl_versandkosten'] ?? '',
					'link'                     => $zp['link'] ?? '',
				);
			}
		}
	}
	
	/* Günstigsten Preis berechnen */
	$min_price = min( array_map( function( $item ) {
		return floatval( str_replace( ',', '.', $item['preis'] ) );
	}, $all_prices ) );

	if ( $all_prices ) {
		$output .= '<div class="tsprodukt-weitere-preise-wrapper">';

		foreach ( $all_prices as $price_item ) {

			$float_preis_zp = floatval( str_replace( ',', '.', $price_item['preis'] ) );
			$anzeige_preis  = number_format( $float_preis_zp, 2, ',', '.' ) . ' €';
			$is_lowest = ( $float_preis_zp == $min_price );

			/* Versand- & Prime-Hinweis aufbauen */
			$versand_html = '';
			if ( ! empty( $price_item['versandkosten_kostenfrei'] ) && '1' === $price_item['versandkosten_kostenfrei'] ) {
				$versand_html = '<span class="tsprodukt-weitere-preise-versand"><img src="' . esc_url( plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/images/icon-vorteile-2.webp' ) . '" alt="" width="15" height="15"> ' . esc_html__( 'Kostenfreie Lieferung', 'boxyfy' ) . '</span>';
			} elseif ( ! empty( $price_item['inkl_versandkosten'] ) ) {
				$versand_html = '<span class="tsprodukt-weitere-preise-versand">' . esc_html__( 'inkl. Versand:', 'boxyfy' ) . ' ' . esc_html( $price_item['inkl_versandkosten'] ) . ' €</span>';
			} elseif ( ! empty( $price_item['zzgl_versandkosten'] ) ) {
				$versand_html = '<span class="tsprodukt-weitere-preise-versand">' . esc_html__( 'zzgl. Versand:', 'boxyfy' ) . ' ' . esc_html( $price_item['zzgl_versandkosten'] ) . ' €</span>';
			}

			$prime_html = '';
			if ( 'Amazon' === $price_item['shop'] ) {
				if ( 'yes' === $price_item['prime_status'] ) {
					$prime_html = '<span class="prime-status-produktseite-box"><img src="' . esc_url( plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/images/icon-vorteile-2.webp' ) . '" alt="" width="15" height="15"> ' . esc_html__( 'Kostenloser Versand mit Prime', 'boxyfy' ) . '</span>';
				} elseif ( 'no' === $price_item['prime_status'] ) {
					$prime_html = '<span class="prime-status-produktseite-box not-available">' . esc_html__( 'Kein kostenloser Versand mit Prime', 'boxyfy' ) . '</span>';
				}
			}

			/* ───────── Einzelner Preis-Block ───────── */
			$output .= '<div class="tsprodukt-weitere-preise-item">';

			/* 1. Zeile: Shop-Name & Preis UNTEREINANDER, Button rechts      */
			$output .= '	<div class="tsprodukt-weitere-preise-toprow">';

			$output .= '		<div class="tsprodukt-weitere-preise-shopcol">';
			$output .=				esc_html( $price_item['shop'] );
			$output .= '			<span class="tsprodukt-weitere-preise-preis">' . $anzeige_preis . '</span>';
			if ( $is_lowest ) {
				$output .= '			<div class="tsprodukt-bester-preis-label">' . esc_html__( 'Günstigster Preis', 'boxyfy' ) . '</div>';
			}
			$output .= '		</div>';
			$output .= '		<div class="tsprodukt-weitere-preise-buttoncol">';
			if ( ! empty( $price_item['link'] ) ) {
				$output .= '		<a href="' . esc_url( $price_item['link'] ) . '" class="tsprodukt-weitere-preise-button" target="_blank" rel="nofollow">
									<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22" width="22" height="22"><path d="M19.5 8.25H16.5V7.75C16.5 6.55653 16.0259 5.41193 15.182 4.56802C14.3381 3.72411 13.1935 3.25 12 3.25C10.8065 3.25 9.66193 3.72411 8.81802 4.56802C7.97411 5.41193 7.5 6.55653 7.5 7.75V8.25H4.5C4.16848 8.25 3.85054 8.3817 3.61612 8.61612C3.3817 8.85054 3.25 9.16848 3.25 9.5V18C3.25 18.7293 3.53973 19.4288 4.05546 19.9445C4.57118 20.4603 5.27065 20.75 6 20.75H18C18.7293 20.75 19.4288 20.4603 19.9445 19.9445C20.4603 19.4288 20.75 18.7293 20.75 18V9.5C20.75 9.16848 20.6183 8.85054 20.3839 8.61612C20.1495 8.3817 19.8315 8.25 19.5 8.25ZM9 7.75C9 6.95435 9.31607 6.19129 9.87868 5.62868C10.4413 5.06607 11.2044 4.75 12 4.75C12.7956 4.75 13.5587 5.06607 14.1213 5.62868C14.6839 6.19129 15 6.95435 15 7.75V8.25H9V7.75ZM19.25 18C19.25 18.3315 19.1183 18.6495 18.8839 18.8839C18.6495 19.1183 18.3315 19.25 18 19.25H6C5.66848 19.25 5.35054 19.1183 5.11612 18.8839C4.8817 18.6495 4.75 18.3315 4.75 18V9.75H7.5V12C7.5 12.1989 7.57902 12.3897 7.71967 12.5303C7.86032 12.671 8.05109 12.75 8.25 12.75C8.44891 12.75 8.63968 12.671 8.78033 12.5303C8.92098 12.3897 9 12.1989 9 12V9.75H15V12C15 12.1989 15.079 12.3897 15.2197 12.5303C15.3603 12.671 15.5511 12.75 15.75 12.75C15.9489 12.75 16.1397 12.671 16.2803 12.5303C16.421 12.3897 16.5 12.1989 16.5 12V9.75H19.25V18Z" fill="currentColor"/></svg>
									' . esc_html( $box_shop_button_text ) . '</a>';
			}
			$output .= '		</div>';

			$output .= '	</div>'; // .toprow

			/* 2. Zeile: Versand- & Prime-Infos */
			if ( $versand_html || $prime_html ) {
				$output .= '<div class="tsprodukt-weitere-preise-shipping-row">';
				$output .= $versand_html . $prime_html;
				$output .= '</div>';
			}

			$output .= '</div>'; // .tsprodukt-weitere-preise-item
		}
		$output .= '</div>'; // .tsprodukt-weitere-preise-wrapper
	}

	/* ─────────────────────────
	 * 10) Labels (Sieger, Highlight …)
	 * ───────────────────────── */
	$labels         = get_post_meta( $post_id, '_boxyfy_produktlabels', true );
	$custom_label   = get_post_meta( $post_id, '_boxyfy_custom_label', true );
	$label_counter  = 0;

	if ( $labels && is_array( $labels ) ) {
		foreach ( $labels as $l ) {
			$pos_class = ( 0 === $label_counter ) ? 'label1-first' : ( 1 === $label_counter ? 'label1-second' : '' );

			switch ( $l ) {
				case 'preissieger':
					$output .= '<div class="ts-produktlabel-einzelbox label1 ' . esc_attr( $pos_class ) . '">' . esc_html__( 'Preissieger', 'boxyfy' ) . '</div>';
					break;
				case 'vergleichssieger':
					$output .= '<div class="ts-produktlabel-einzelbox label1 ' . esc_attr( $pos_class ) . '">' . esc_html__( 'Vergleichssieger', 'boxyfy' ) . '</div>';
					break;
				case 'highlight':
					$output .= '<div class="ts-produktlabel-einzelbox label1 ' . esc_attr( $pos_class ) . '">' . esc_html__( 'Highlight', 'boxyfy' ) . '</div>';
					break;
				case 'testsieger':
					$output .= '<div class="ts-produktlabel-einzelbox label1 ' . esc_attr( $pos_class ) . '">' . esc_html__( 'Testsieger', 'boxyfy' ) . '</div>';
					break;
			}
			$label_counter ++;
		}
	}

	if ( $custom_label ) {
		$output .= '<div class="ts-produktlabel-einzelbox label2">' . esc_html( $custom_label ) . '</div>';
	}

	$output .= '</div><!-- .tsprodukt-box-content -->';
	$output .= '</div><!-- .tsprodukt-box -->';

	return $output;
}
add_shortcode( 'boxyfy_produktbox', 'boxyfy_shortcode_box' );

/* ────────────────────────────
 *  KI-Chat-AJAX-Calls bleiben
 * ──────────────────────────── */
add_action( 'wp_ajax_boxyfy_ai_generate_questions', 'boxyfy_ai_generate_questions' );
add_action( 'wp_ajax_nopriv_boxyfy_ai_generate_questions', 'boxyfy_ai_generate_questions' );

function boxyfy_ai_generate_questions() {
	if ( 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
		wp_send_json_error( array( 'message' => 'Nur POST erlaubt' ), 405 );
	}
	check_ajax_referer( 'boxyfy_ai_nonce', 'nonce' );

	$title = sanitize_text_field( $_POST['product_title'] ?? '' );

	$resp = wp_remote_post(
		'https://test-im-netz.de/perplexity-proxy.php',
		array(
			'body'    => array(
				'type'          => 'generate_questions',
				'product_title' => $title,
			),
			'timeout' => 20,
		)
	);

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

	$code = wp_remote_retrieve_response_code( $resp );
	if ( 200 !== $code ) {
		wp_send_json_error( array( 'message' => "Proxy-Server-Fehler: {$code}" ), $code );
	}

	wp_send_json_success( json_decode( wp_remote_retrieve_body( $resp ), true ) );
}

add_action( 'wp_ajax_boxyfy_ai_ask_question', 'boxyfy_ai_ask_question' );
add_action( 'wp_ajax_nopriv_boxyfy_ai_ask_question', 'boxyfy_ai_ask_question' );

function boxyfy_ai_ask_question() {
	if ( 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
		wp_send_json_error( array( 'message' => 'Nur POST erlaubt' ), 405 );
	}
	check_ajax_referer( 'boxyfy_ai_nonce', 'nonce' );

	$question = sanitize_textarea_field( $_POST['user_question'] ?? '' );

	$resp = wp_remote_post(
		'https://test-im-netz.de/perplexity-proxy.php',
		array(
			'body'    => array(
				'type'          => 'ask_question',
				'user_question' => $question,
			),
			'timeout' => 20,
		)
	);

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

	$code = wp_remote_retrieve_response_code( $resp );
	if ( 200 !== $code ) {
		wp_send_json_error( array( 'message' => "Proxy-Server-Fehler: {$code}" ), $code );
	}

	wp_send_json_success( json_decode( wp_remote_retrieve_body( $resp ), true ) );
}