| 1 |
<?php |
| 2 |
|
| 3 |
namespace RadiusTheme\SB\AI\Ajax; |
| 4 |
|
| 5 |
// Do not allow directly accessing this file. |
| 6 |
use RadiusTheme\SB\AI\AIFns; |
| 7 |
use RadiusTheme\SB\AI\Embedding\DataEmbedding; |
| 8 |
use RadiusTheme\SB\Traits\SingletonTrait; |
| 9 |
|
| 10 |
if ( ! defined( 'ABSPATH' ) ) { |
| 11 |
exit( 'This script cannot be accessed directly.' ); |
| 12 |
} |
| 13 |
|
| 14 |
/** |
| 15 |
* AIPower Model |
| 16 |
* |
| 17 |
* Manages AI service initialization and adapter creation for various AI providers |
| 18 |
* including OpenAI, Gemini, and DeepSeek. |
| 19 |
* |
| 20 |
* @since 1.0.0 |
| 21 |
*/ |
| 22 |
class AjaxAI { |
| 23 |
/** |
| 24 |
* Singleton Trait. |
| 25 |
*/ |
| 26 |
use SingletonTrait; |
| 27 |
|
| 28 |
/** |
| 29 |
* AJAX handler for generating AI content |
| 30 |
* |
| 31 |
* @return void |
| 32 |
*/ |
| 33 |
public function generate_product_content() { |
| 34 |
check_ajax_referer( 'rtsb_ai_nonce', 'nonce' ); |
| 35 |
if ( ! current_user_can( 'edit_posts' ) ) { |
| 36 |
wp_send_json_error( [ 'message' => __( 'Permission denied', 'shopbuilder' ) ] ); |
| 37 |
} |
| 38 |
$content_type = sanitize_text_field( wp_unslash( $_POST['content_type'] ?? '' ) ); |
| 39 |
$instruction = isset( $_POST['instruction'] ) ? sanitize_text_field( wp_unslash( $_POST['instruction'] ) ) : ''; |
| 40 |
|
| 41 |
try { |
| 42 |
$ai_service = AIFns::initializeAIService(); |
| 43 |
$generated_content = $ai_service->generateResponse( $content_type, $instruction ); |
| 44 |
wp_send_json_success( |
| 45 |
[ |
| 46 |
'content' => $generated_content, |
| 47 |
'type' => $content_type, |
| 48 |
] |
| 49 |
); |
| 50 |
} catch ( \Exception $e ) { |
| 51 |
wp_send_json_error( [ 'message' => $e->getMessage() ] ); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* @return void |
| 57 |
*/ |
| 58 |
public function semantic_search_suggestions() { |
| 59 |
check_ajax_referer( 'rtsb_nonce', 'nonce' ); |
| 60 |
$query = sanitize_text_field( wp_unslash( $_GET['searchTerm'] ?? '' ) ); |
| 61 |
$limit = absint( wp_unslash( $_GET['product_limit'] ?? 5 ) ); |
| 62 |
$service = DataEmbedding::instance(); |
| 63 |
$similar_posts = $service->search( $query, $limit ); |
| 64 |
$suggestions = ! empty( $similar_posts ) ? $similar_posts : []; |
| 65 |
wp_send_json_success( |
| 66 |
[ |
| 67 |
'suggestions' => $suggestions, |
| 68 |
] |
| 69 |
); |
| 70 |
} |
| 71 |
} |
| 72 |
|