<?php
defined('ABSPATH') or die();
use AiomaticOpenAI\OpenAi\OpenAi;
if(!class_exists('Aiomatic_Embeddings')) {
    class Aiomatic_Embeddings
    {
        private static  $instance = null ;
        private  $api_key = '' ;
        public static function get_instance($api_key)
        {
            if(self::$instance && self::$instance->api_key !== $api_key)
            {
                self::$instance = new self($api_key);
            }
            if ( is_null( self::$instance ) ) {
                self::$instance = new self($api_key);
            }
            return self::$instance;
        }

        public function __construct($api_key)
        {
            if(!aiomatic_is_aiomaticapi_key($api_key))
            {
                require_once (dirname(__FILE__) . "/openai/Url.php"); 
                require_once (dirname(__FILE__) . "/openai/OpenAi.php");
            }
            add_action('wp_ajax_aiomatic_embeddings', [$this, 'aiomatic_embeddings']);
            $this->api_key = $api_key;
        }

        public function aimogenpro_save_embedding($content, $post_type = '', $title = '', $embaddings_id = false, $model = AIMOGEN_DEFAULT_MODEL_EMBEDDING, $namespace = '')
        {
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings saving');
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if (!isset($aiomatic_Main_Settings['app_id']) || trim($aiomatic_Main_Settings['app_id']) == '') 
            {
                $aiomatic_result['msg'] = 'Missing API Setting';
                return $aiomatic_result;
            }
            else 
            {
                if (!isset($aiomatic_Main_Settings['api_selector']) || trim($aiomatic_Main_Settings['api_selector']) != 'azure') 
                {
                    if(!aiomatic_is_aiomaticapi_key($this->api_key))
                    {
                        $openai = new OpenAi($this->api_key);
                        if (isset($aiomatic_Main_Settings['api_selector']) && trim($aiomatic_Main_Settings['api_selector']) == 'custom' && isset($aiomatic_Main_Settings['custom_endpoint']) && trim($aiomatic_Main_Settings['custom_endpoint'], ' /') != '') 
                        {
                            $openai->setCustomURL(trim($aiomatic_Main_Settings['custom_endpoint'], ' /'));
                        }
                        if (isset($aiomatic_Main_Settings['openai_organization']) && $aiomatic_Main_Settings['openai_organization'] != '')
                        {
                            $openai->setORG($aiomatic_Main_Settings['openai_organization']);
                        }
                    }
                    else
                    {
                        $openai = true;
                    }
                }
                else
                {
                    $openai = true;
                }
            }
            $max_tokens = aimogenpro_get_max_input_tokens($model);
            $in_tokens = count(aiomatic_encode($content));
            if($in_tokens > $max_tokens)
            {
                $content = aiomatic_strip_to_token_count($content, aimogenpro_get_max_input_tokens($model), false);
            }
            if ((!isset($aiomatic_Main_Settings['embeddings_api']) || trim($aiomatic_Main_Settings['embeddings_api']) == '') || (isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'pinecone'))
            {
                if (!isset($aiomatic_Main_Settings['pinecone_app_id']) || trim($aiomatic_Main_Settings['pinecone_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                    return $aiomatic_result;
                }
                if (!isset($aiomatic_Main_Settings['pinecone_index']) || trim($aiomatic_Main_Settings['pinecone_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                    return $aiomatic_result;
                }
                $token = $this->api_key;
                $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
                if($openai)
                {
                    $aiomatic_pinecone_api = trim($aiomatic_Main_Settings['pinecone_app_id']);
                    $aiomatic_pinecone_environment = preg_replace("(^https?:\/\/)", "", trim($aiomatic_Main_Settings['pinecone_index']));
                    $headers = array(
                        'Content-Type' => 'application/json',
                        'Api-Key' => $aiomatic_pinecone_api
                    );
                    $response = wp_remote_get('https://'.$aiomatic_pinecone_environment, array(
                        'headers' => $headers,
                        'timeout' => 60
                    ));
                    if(is_wp_error($response)){
                        $aiomatic_result['msg'] = $response->get_error_message();
                        return $aiomatic_result;
                    }

                    $response_code = $response['response']['code'];
                    if($response_code !== 200){
                        $aiomatic_result['msg'] = $response['body'];
                        if(empty($aiomatic_result['msg'] ))
                        {
                            $aiomatic_result['msg'] = 'Error code returned for Pinecone Index: ' . $aiomatic_Main_Settings['pinecone_index'] . ': ' . $response_code . ' - index: ' . 'https://' . $aiomatic_pinecone_environment . '/databases';
                        }
                        return $aiomatic_result;
                    }
                    $embedding = '';
                    $session = aiomatic_get_session_id();
                    $maxResults = 1;
                    $query = new Aiomatic_Query($content, 2048, $model, 0, '', 'saveembeddings', 'embeddings', $token, $session, $maxResults, '', '');
                    if(aiomatic_is_ollama_embeddings_model($model))
                    {
                        $error = '';
                        $response = aiomatic_generate_embeddings_ollama($model, $content, $error);
                        if($response === false)
                        {
                            $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                            return $aiomatic_result;
                        }
                        if(isset($response['error']))
                        {
                            $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                            return $aiomatic_result;
                        }
                        $embedding = $response;
                    }
                    else
                    {
                        if(aiomatic_google_extension_is_google_embeddings_model($model))
                        {
                            $error = '';
                            $response = aiomatic_generate_embeddings_google($model, $content, $error);
                            if($response === false)
                            {
                                $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                return $aiomatic_result;
                            }
                            if(isset($response['error']))
                            {
                                $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                                return $aiomatic_result;
                            }
                            $embedding = $response;
                        }
                        else
                        {
                            if(aiomatic_is_aiomaticapi_key($this->api_key))
                            {
                                $error = '';
                                $response = aiomatic_embeddings_aiomaticapi($token, $model, $content, 0, $error);
                                if($response === false)
                                {
                                    $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                    return $aiomatic_result;
                                }
                                if(isset($response->error))
                                {
                                    $aiomatic_result['data'] = 'Error while processing AI response: ' . $response->error;
                                    return $aiomatic_result;
                                }
                                if(!isset($response[0]->embedding))
                                {
                                    $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . print_r($response, true);
                                    return $aiomatic_result;
                                }
                                apply_filters( 'aiomatic_ai_reply', $response, $query );
                                $embedding = $response[0]->embedding;
                            }
                            else
                            {
                                if (aiomatic_check_if_azure($aiomatic_Main_Settings)) 
                                {
                                    $error = '';
                                    $response = aiomatic_embeddings_azure($token, $model, $content, 0, $error);
                                    if($response === false)
                                    {
                                        $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                        return $aiomatic_result;
                                    }
                                    else
                                    {
                                        $embedding = (array)$response[0]->embedding;
                                        apply_filters( 'aiomatic_ai_reply', $response, $query );
                                    }
                                }
                                else
                                {
                                    $response = $openai->embeddings(array(
                                        'input' => $content,
                                        'model' => $model
                                    ));
                                
                                    $response = json_decode($response, true);
                                    if(isset($response['error']) && !empty($response['error'])) {
                                        $aiomatic_result['msg'] = $response['error']['message'];
                                    }
                                    else{
                                        if(
                                            !isset($response['data'][0]['embedding'])
                                        )
                                        {
                                            $aiomatic_result['msg'] = 'Invalid embedding response';
                                            return $aiomatic_result;
                                        }
                                        $embedding = $response['data'][0]['embedding'];
                                        apply_filters( 'aiomatic_ai_reply', $response, $query );
                                    }
                                }
                            }
                        }
                    }
                    if(empty($embedding))
                    {
                        if($aiomatic_result['msg'] == 'Something went wrong with embeddings processing')
                        {
                            $aiomatic_result['msg'] = 'No data returned';
                        }
                    }
                    else
                    {
                        $pinecone_url = 'https://' . $aiomatic_pinecone_environment . '/vectors/upsert';
                        if(!$embaddings_id) {
                            if(function_exists('mb_substr'))
                            {
                                $embedding_title = empty($title) ? mb_substr($content, 0, 50, 'UTF-8') : $title;
                            }
                            else
                            {
                                $embedding_title = empty($title) ? substr($content, 0, 50) : $title;
                            }
                            $embedding_data = array(
                                'post_type' => 'aiomatic_embeddings',
                                'post_title' => $embedding_title,
                                'post_content' => $content,
                                'post_status' => 'publish'
                            );
                            if (!empty($post_type)) {
                                $embedding_data['post_type'] = $post_type;
                            }
                            remove_filter('content_save_pre', 'wp_filter_post_kses');
                            remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                            $embaddings_id = wp_insert_post($embedding_data);
                            add_filter('content_save_pre', 'wp_filter_post_kses');
                            add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                        }
                        if(is_wp_error($embaddings_id))
                        {
                            $aiomatic_result['msg'] = $embaddings_id->get_error_message();
                        }
                        elseif($embaddings_id === 0)
                        {
                            $aiomatic_result['msg'] = 'Failed to insert embedding to database: ' . $embedding_title;
                        }
                        else 
                        {
                            if(empty($namespace))
                            {
                                if (isset($aiomatic_Main_Settings['pinecone_namespace']) && trim($aiomatic_Main_Settings['pinecone_namespace']) != '')
                                {
                                    update_post_meta($embaddings_id, 'aiomatic_namespace', trim($aiomatic_Main_Settings['pinecone_namespace']));
                                }
                            }
                            else
                            {
                                update_post_meta($embaddings_id, 'aiomatic_namespace', trim($namespace));
                            }
                            update_post_meta($embaddings_id, 'aiomatic_start',time());
                            if(aiomatic_is_aiomaticapi_key($this->api_key) || (aiomatic_check_if_azure($aiomatic_Main_Settings)))
                            {
                                $usage_tokens = count(aiomatic_encode($content));
                            }
                            else
                            {
                                if(isset($response['usage']['total_tokens']))
                                {
                                    $usage_tokens = $response['usage']['total_tokens'];
                                }
                                else
                                {
                                    $usage_tokens = count(aiomatic_encode($content));
                                }
                            }
                            update_post_meta($embaddings_id, 'aiomatic_embedding_token', $usage_tokens);
                            update_post_meta($embaddings_id, 'aiomatic_embedding_model', $model);
                            $vectors = array(
                                array(
                                    'id' => (string)$embaddings_id,
                                    'values' => $embedding
                                )
                            );
                            $sendjs = array('vectors' => $vectors);
                            if(empty($namespace))
                            {
                                if (isset($aiomatic_Main_Settings['pinecone_namespace']) && trim($aiomatic_Main_Settings['pinecone_namespace']) != '')
                                {
                                    $sendjs['namespace'] = trim($aiomatic_Main_Settings['pinecone_namespace']);
                                }
                            }
                            else
                            {
                                $sendjs['namespace'] = trim($namespace);
                            }
                            $response = wp_remote_post($pinecone_url, array(
                                'headers' => $headers,
                                'body' => json_encode($sendjs),
                                'timeout' => 60
                            ));
                            if(is_wp_error($response))
                            {
                                $aiomatic_result['msg'] = $response->get_error_message();
                                wp_delete_post($embaddings_id, true);
                            }
                            else
                            {
                                $body = json_decode($response['body'],true);
                                if($body)
                                {
                                    if(isset($body['code']) && isset($body['message']))
                                    {
                                        $aiomatic_result['msg'] = strip_tags($body['message']);
                                        wp_delete_post($embaddings_id, true);
                                    }
                                    else
                                    {
                                        $aiomatic_result['status'] = 'success';
                                        $aiomatic_result['id'] = $embaddings_id;
                                        update_post_meta($embaddings_id, 'aiomatic_completed', time());
                                    }
                                }
                                else
                                {
                                    $aiomatic_result['msg'] = 'No data returned';
                                    wp_delete_post($embaddings_id, true);
                                }
                            }
                        }
                    }
                }
                else
                {
                    $aiomatic_result['msg'] = 'Missing OpenAI API Settings';
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'openai')
            {
                require_once (dirname(__FILE__) . "/aiomatic-assistants-api.php");
                if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
                {
                    $aiomatic_result['msg'] = 'You must add an OpenAI API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                    return $aiomatic_result;
                }

                $token = $this->api_key;
                $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);

                if($openai)
                {
                    $vector_store_id = '';

                    if(!empty($namespace))
                    {
                        $vector_store_id = trim($namespace);
                    }
                    elseif(isset($aiomatic_Main_Settings['openai_vector_store_ids']) && !empty($aiomatic_Main_Settings['openai_vector_store_ids']))
                    {
                        if(is_array($aiomatic_Main_Settings['openai_vector_store_ids']))
                        {
                            $vector_store_id = trim(reset($aiomatic_Main_Settings['openai_vector_store_ids']));
                        }
                        else
                        {
                            $tmp_vector_store_ids = array_map('trim', explode(',', $aiomatic_Main_Settings['openai_vector_store_ids']));
                            $tmp_vector_store_ids = array_values(array_filter($tmp_vector_store_ids));

                            if(!empty($tmp_vector_store_ids))
                            {
                                $vector_store_id = $tmp_vector_store_ids[0];
                            }
                        }
                    }
                    elseif(isset($aiomatic_Main_Settings['openai_vector_store_id']) && trim($aiomatic_Main_Settings['openai_vector_store_id']) != '')
                    {
                        $vector_store_id = trim($aiomatic_Main_Settings['openai_vector_store_id']);
                    }

                    try
                    {
                        if($vector_store_id == '')
                        {
                            $created_store = aiomatic_openai_create_vector_store($token, 'Aiomatic Vector Store');

                            if(empty($created_store['id']))
                            {
                                throw new Exception('OpenAI Vector Store creation failed: no vector store ID returned.');
                            }

                            $vector_store_id = $created_store['id'];

                            $aiomatic_Main_Settings['openai_vector_store_id'] = $vector_store_id;

                            if(
                                !isset($aiomatic_Main_Settings['openai_vector_store_ids']) ||
                                empty($aiomatic_Main_Settings['openai_vector_store_ids'])
                            ) {
                                $aiomatic_Main_Settings['openai_vector_store_ids'] = array($vector_store_id);
                            }

                            update_option('aiomatic_Main_Settings', $aiomatic_Main_Settings);
                        }

                        $created_embedding_post = false;
                        $temp_file = '';

                        if(!$embaddings_id) 
                        {
                            if(function_exists('mb_substr'))
                            {
                                $embedding_title = empty($title) ? mb_substr($content, 0, 50, 'UTF-8') : $title;
                            }
                            else
                            {
                                $embedding_title = empty($title) ? substr($content, 0, 50) : $title;
                            }

                            $embedding_data = array(
                                'post_type'    => 'aiomatic_embeddings',
                                'post_title'   => $embedding_title,
                                'post_content' => $content,
                                'post_status'  => 'publish'
                            );

                            if (!empty($post_type)) 
                            {
                                $embedding_data['post_type'] = $post_type;
                            }

                            remove_filter('content_save_pre', 'wp_filter_post_kses');
                            remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
                            remove_filter('title_save_pre', 'wp_filter_kses');

                            $embaddings_id = wp_insert_post($embedding_data);

                            add_filter('content_save_pre', 'wp_filter_post_kses');
                            add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
                            add_filter('title_save_pre', 'wp_filter_kses');

                            $created_embedding_post = true;
                        }

                        if(is_wp_error($embaddings_id))
                        {
                            $aiomatic_result['msg'] = $embaddings_id->get_error_message();
                            return $aiomatic_result;
                        }

                        if($embaddings_id === 0)
                        {
                            $aiomatic_result['msg'] = 'Failed to insert embedding to database.';
                            return $aiomatic_result;
                        }

                        update_post_meta($embaddings_id, 'aiomatic_namespace', $vector_store_id);
                        update_post_meta($embaddings_id, 'aiomatic_start', time());
                        update_post_meta($embaddings_id, 'aiomatic_embedding_token', count(aiomatic_encode($content)));
                        update_post_meta($embaddings_id, 'aiomatic_embedding_model', $model);

                        $upload_dir = wp_upload_dir();

                        if(!empty($upload_dir['error']))
                        {
                            throw new Exception($upload_dir['error']);
                        }

                        $old_vector_store_id = get_post_meta($embaddings_id, 'openai_vector_store_id', true);
                        $old_openai_file_id = get_post_meta($embaddings_id, 'openai_file_id', true);

                        if(!empty($old_vector_store_id) && !empty($old_openai_file_id))
                        {
                            try
                            {
                                aiomatic_openai_delete_vector_store_file($token, $old_vector_store_id, $old_openai_file_id);
                            }
                            catch(Exception $delete_e)
                            {
                                // Ignore old file delete errors, continue with new upload.
                            }
                        }
                        $safe_name = sanitize_file_name('aiomatic-embedding-' . $embaddings_id . '-' . time() . '.txt');
                        $temp_file = trailingslashit($upload_dir['path']) . $safe_name;

                        $file_content  = 'Title: ' . get_the_title($embaddings_id) . "\n";
                        $file_content .= 'Post ID: ' . $embaddings_id . "\n";
                        $file_content .= 'Source: aiomatic' . "\n\n";
                        $file_content .= $content;

                        if(file_put_contents($temp_file, $file_content) === false)
                        {
                            throw new Exception('Failed to create temporary file for OpenAI Vector Store upload.');
                        }

                        if(!function_exists('aiomatic_openai_upload_vector_store_file'))
                        {
                            throw new Exception('OpenAI Vector Store file upload helper is missing.');
                        }

                        $uploaded_file = aiomatic_openai_upload_vector_store_file($token, $temp_file);

                        if(isset($uploaded_file['error']['message']))
                        {
                            throw new Exception($uploaded_file['error']['message']);
                        }

                        if(empty($uploaded_file['id']))
                        {
                            throw new Exception('OpenAI file upload failed: no file ID returned.');
                        }

                        $openai_file_id = $uploaded_file['id'];

                        $attached_file = aiomatic_openai_create_vector_store_file(
                            $token,
                            $vector_store_id,
                            $openai_file_id
                        );

                        if(empty($attached_file['id']) && empty($attached_file['file_id']))
                        {
                            throw new Exception('OpenAI Vector Store file attach failed.');
                        }

                        update_post_meta($embaddings_id, 'aiomatic_completed', time());
                        update_post_meta($embaddings_id, 'openai_vector_store_id', $vector_store_id);
                        update_post_meta($embaddings_id, 'openai_file_id', $openai_file_id);

                        if(!empty($attached_file['id']))
                        {
                            update_post_meta($embaddings_id, 'openai_vector_store_file_id', $attached_file['id']);
                        }

                        /*
                        * Compatibility only. Remove later when all old Qdrant/Chroma lookup code is gone.
                        */
                        update_post_meta($embaddings_id, 'chroma_id', $openai_file_id);
                        update_post_meta($embaddings_id, 'chroma_vector_id', $openai_file_id);
                        update_post_meta($embaddings_id, 'quadrant_id', $openai_file_id);

                        $aiomatic_result['status'] = 'success';
                        $aiomatic_result['id'] = $embaddings_id;
                    }
                    catch(Exception $e)
                    {
                        $aiomatic_result['msg'] = 'OpenAI Vector Store exception: ' . $e->getMessage();

                        if(isset($created_embedding_post) && $created_embedding_post && !empty($embaddings_id) && !is_wp_error($embaddings_id))
                        {
                            wp_delete_post($embaddings_id, true);
                        }
                    }

                    if(isset($temp_file) && $temp_file != '' && file_exists($temp_file))
                    {
                        @unlink($temp_file);
                    }
                }
                else
                {
                    $aiomatic_result['msg'] = 'Missing OpenAI API Settings';
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'chroma')
            {
                if (!isset($aiomatic_Main_Settings['chroma_app_id']) || trim($aiomatic_Main_Settings['chroma_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                    return $aiomatic_result;
                }

                if (!isset($aiomatic_Main_Settings['chroma_index']) || trim($aiomatic_Main_Settings['chroma_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma URL in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                    return $aiomatic_result;
                }

                $token = $this->api_key;
                $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);

                if($openai)
                {
                    require_once (dirname(__FILE__) . "/Chroma.php");

                    $chroma_api_key = trim($aiomatic_Main_Settings['chroma_app_id']);
                    $chroma_url = aimogenpro_chroma_normalize_base_url($aiomatic_Main_Settings['chroma_index']);

                    if(isset($aiomatic_Main_Settings['chroma_tennant']) && trim($aiomatic_Main_Settings['chroma_tennant']) != '')
                    {
                        $chroma_tenant = trim($aiomatic_Main_Settings['chroma_tennant']);
                    }
                    elseif(isset($aiomatic_Main_Settings['chroma_tenant']) && trim($aiomatic_Main_Settings['chroma_tenant']) != '')
                    {
                        $chroma_tenant = trim($aiomatic_Main_Settings['chroma_tenant']);
                    }
                    else
                    {
                        $chroma_tenant = 'default_tenant';
                    }

                    if(isset($aiomatic_Main_Settings['chroma_database']) && trim($aiomatic_Main_Settings['chroma_database']) != '')
                    {
                        $chroma_database = trim($aiomatic_Main_Settings['chroma_database']);
                    }
                    else
                    {
                        $chroma_database = 'default_database';
                    }

                    $embedding = '';
                    $session = aiomatic_get_session_id();
                    $maxResults = 1;

                    $query = new Aiomatic_Query($content, 2048, $model, 0, '', 'saveembeddings', 'embeddings', $token, $session, $maxResults, '', '');

                    if(aiomatic_is_ollama_embeddings_model($model))
                    {
                        $error = '';
                        $response = aiomatic_generate_embeddings_ollama($model, $content, $error);

                        if($response === false)
                        {
                            $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                            return $aiomatic_result;
                        }

                        if(isset($response['error']))
                        {
                            $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                            return $aiomatic_result;
                        }

                        $embedding = $response;
                        apply_filters('aiomatic_ai_reply', $response, $query);
                    }
                    else
                    {
                        if(aiomatic_google_extension_is_google_embeddings_model($model))
                        {
                            $error = '';
                            $response = aiomatic_generate_embeddings_google($model, $content, $error);

                            if($response === false)
                            {
                                $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                return $aiomatic_result;
                            }

                            if(isset($response['error']))
                            {
                                $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                                return $aiomatic_result;
                            }

                            $embedding = $response;
                            apply_filters('aiomatic_ai_reply', $response, $query);
                        }
                        else
                        {
                            if(aiomatic_is_aiomaticapi_key($this->api_key))
                            {
                                $error = '';
                                $response = aiomatic_embeddings_aiomaticapi($token, $model, $content, 0, $error);

                                if($response === false)
                                {
                                    $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                    return $aiomatic_result;
                                }

                                if(isset($response->error))
                                {
                                    $aiomatic_result['data'] = 'Error while processing AI response: ' . $response->error;
                                    return $aiomatic_result;
                                }

                                if(!isset($response[0]->embedding))
                                {
                                    $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . print_r($response, true);
                                    return $aiomatic_result;
                                }

                                apply_filters('aiomatic_ai_reply', $response, $query);
                                $embedding = $response[0]->embedding;
                            }
                            else
                            {
                                if (aiomatic_check_if_azure($aiomatic_Main_Settings)) 
                                {
                                    $error = '';
                                    $response = aiomatic_embeddings_azure($token, $model, $content, 0, $error);

                                    if($response === false)
                                    {
                                        $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                        return $aiomatic_result;
                                    }

                                    if(isset($response->error))
                                    {
                                        $aiomatic_result['data'] = 'Error while processing AI response: ' . $response->error;
                                        return $aiomatic_result;
                                    }

                                    if(!isset($response[0]->embedding))
                                    {
                                        $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . print_r($response, true);
                                        return $aiomatic_result;
                                    }

                                    $embedding = (array)$response[0]->embedding;
                                    apply_filters('aiomatic_ai_reply', $response, $query);
                                }
                                else
                                {
                                    $response = $openai->embeddings(array(
                                        'input' => $content,
                                        'model' => $model
                                    ));

                                    $response = json_decode($response, true);

                                    if(isset($response['error']) && !empty($response['error'])) 
                                    {
                                        if(isset($response['error']['message']))
                                        {
                                            $aiomatic_result['msg'] = $response['error']['message'];
                                        }
                                        else
                                        {
                                            $aiomatic_result['msg'] = print_r($response['error'], true);
                                        }

                                        return $aiomatic_result;
                                    }
                                    else
                                    {
                                        if(!isset($response['data'][0]['embedding']))
                                        {
                                            $aiomatic_result['msg'] = 'Invalid embedding response';
                                            return $aiomatic_result;
                                        }

                                        $embedding = $response['data'][0]['embedding'];
                                        apply_filters('aiomatic_ai_reply', $response, $query);
                                    }
                                }
                            }
                        }
                    }

                    if(empty($embedding))
                    {
                        if($aiomatic_result['msg'] == 'Something went wrong with embeddings processing')
                        {
                            $aiomatic_result['msg'] = 'No data returned';
                        }
                    }
                    else
                    {
                        if(empty($namespace))
                        {
                            if (isset($aiomatic_Main_Settings['chroma_name']) && trim($aiomatic_Main_Settings['chroma_name']) != '')
                            {
                                $index_name = trim($aiomatic_Main_Settings['chroma_name']);
                            }
                            else
                            {
                                $index_name = 'chroma';
                            }
                        }
                        else
                        {
                            $index_name = trim($namespace);
                        }

                        $created_embedding_post = false;

                        try
                        {
                            $my_indexes = aimogenpro_chroma_list_indexes($chroma_api_key, $chroma_url, $chroma_tenant, $chroma_database);

                            if(is_wp_error($my_indexes))
                            {
                                throw new Exception($my_indexes->get_error_message());
                            }

                            $found = false;

                            foreach($my_indexes as $mid)
                            {
                                if(isset($mid['name']) && $mid['name'] == $index_name)
                                {
                                    $found = true;
                                    break;
                                }
                            }

                            if($found == false)
                            {
                                $created_index = aimogenpro_chroma_add_index($chroma_api_key, $chroma_url, $chroma_tenant, $chroma_database, $index_name);

                                if(is_wp_error($created_index))
                                {
                                    throw new Exception($created_index->get_error_message());
                                }
                            }

                            if(!$embaddings_id) 
                            {
                                if(function_exists('mb_substr'))
                                {
                                    $embedding_title = empty($title) ? mb_substr($content, 0, 50, 'UTF-8') : $title;
                                }
                                else
                                {
                                    $embedding_title = empty($title) ? substr($content, 0, 50) : $title;
                                }

                                $embedding_data = array(
                                    'post_type'    => 'aiomatic_embeddings',
                                    'post_title'   => $embedding_title,
                                    'post_content' => $content,
                                    'post_status'  => 'publish'
                                );

                                if (!empty($post_type)) 
                                {
                                    $embedding_data['post_type'] = $post_type;
                                }

                                remove_filter('content_save_pre', 'wp_filter_post_kses');
                                remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
                                remove_filter('title_save_pre', 'wp_filter_kses');

                                $embaddings_id = wp_insert_post($embedding_data);

                                add_filter('content_save_pre', 'wp_filter_post_kses');
                                add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
                                add_filter('title_save_pre', 'wp_filter_kses');

                                $created_embedding_post = true;
                            }

                            if(is_wp_error($embaddings_id))
                            {
                                $aiomatic_result['msg'] = $embaddings_id->get_error_message();
                            }
                            elseif($embaddings_id === 0)
                            {
                                $aiomatic_result['msg'] = 'Failed to insert embedding to database: ' . $embedding_title;
                            }
                            else 
                            {
                                if(empty($namespace))
                                {
                                    if (isset($aiomatic_Main_Settings['chroma_name']) && trim($aiomatic_Main_Settings['chroma_name']) != '')
                                    {
                                        update_post_meta($embaddings_id, 'aiomatic_namespace', trim($aiomatic_Main_Settings['chroma_name']));
                                    }
                                }
                                else
                                {
                                    update_post_meta($embaddings_id, 'aiomatic_namespace', trim($namespace));
                                }

                                update_post_meta($embaddings_id, 'aiomatic_start', time());

                                if(aiomatic_is_aiomaticapi_key($this->api_key) || aiomatic_check_if_azure($aiomatic_Main_Settings))
                                {
                                    $usage_tokens = count(aiomatic_encode($content));
                                }
                                else
                                {
                                    if(isset($response['usage']['total_tokens']))
                                    {
                                        $usage_tokens = $response['usage']['total_tokens'];
                                    }
                                    else
                                    {
                                        $usage_tokens = count(aiomatic_encode($content));
                                    }
                                }

                                update_post_meta($embaddings_id, 'aiomatic_embedding_token', $usage_tokens);
                                update_post_meta($embaddings_id, 'aiomatic_embedding_model', $model);

                                $chroma_vector_id = (string)$embaddings_id;

                                $vector = array(
                                    'id'       => $chroma_vector_id,
                                    'values'   => $embedding,
                                    'document' => $content,
                                    'metadata' => array(
                                        'source'       => 'aiomatic',
                                        'type'         => !empty($post_type) ? (string)$post_type : 'aiomatic_embeddings',
                                        'title'        => get_the_title($embaddings_id),
                                        'post_id'      => (string)$embaddings_id,
                                        'namespace'    => (string)$index_name,
                                        'model'        => (string)$model,
                                        'created_at'   => (string)time()
                                    )
                                );

                                $chroma_id = aimogenpro_chroma_add_vector(
                                    $chroma_api_key,
                                    $chroma_url,
                                    $chroma_tenant,
                                    $chroma_database,
                                    $index_name,
                                    $vector
                                );

                                if(is_wp_error($chroma_id))
                                {
                                    throw new Exception($chroma_id->get_error_message());
                                }

                                $aiomatic_result['status'] = 'success';
                                $aiomatic_result['id'] = $embaddings_id;

                                update_post_meta($embaddings_id, 'aiomatic_completed', time());
                                update_post_meta($embaddings_id, 'chroma_id', $chroma_id);
                                update_post_meta($embaddings_id, 'chroma_vector_id', $chroma_id);

                                update_post_meta($embaddings_id, 'quadrant_id', $chroma_id);
                            }
                        }
                        catch(Exception $e)
                        {
                            $aiomatic_result['msg'] = 'Chroma exception: ' . $e->getMessage();

                            if($created_embedding_post && !empty($embaddings_id) && !is_wp_error($embaddings_id))
                            {
                                wp_delete_post($embaddings_id, true);
                            }
                        }
                    }
                }
                else
                {
                    $aiomatic_result['msg'] = 'Missing OpenAI API Settings';
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'qdrant')
            {
                if (!isset($aiomatic_Main_Settings['qdrant_app_id']) || trim($aiomatic_Main_Settings['qdrant_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                    return $aiomatic_result;
                }
                if (!isset($aiomatic_Main_Settings['qdrant_index']) || trim($aiomatic_Main_Settings['qdrant_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Quadrant index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                    return $aiomatic_result;
                }
                $token = $this->api_key;
                $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
                if($openai)
                {
                    $aiomatic_qdrant_api = trim($aiomatic_Main_Settings['qdrant_app_id']);
                    $aiomatic_qdrant_environment = rtrim(trim($aiomatic_Main_Settings['qdrant_index'], '/'));
                    $aiomatic_qdrant_environment = preg_replace("(^https?:\/\/)", "", $aiomatic_qdrant_environment);
                    $qdrant_url = 'https://' . $aiomatic_qdrant_environment;
                    $embedding = '';
                    $session = aiomatic_get_session_id();
                    $maxResults = 1;
                    $query = new Aiomatic_Query($content, 2048, $model, 0, '', 'saveembeddings', 'embeddings', $token, $session, $maxResults, '', '');
                    if(aiomatic_is_ollama_embeddings_model($model))
                    {
                        $error = '';
                        $response = aiomatic_generate_embeddings_ollama($model, $content, $error);
                        if($response === false)
                        {
                            $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                            return $aiomatic_result;
                        }
                        if(isset($response['error']))
                        {
                            $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                            return $aiomatic_result;
                        }
                        $embedding = $response;
                    }
                    else
                    {
                        if(aiomatic_google_extension_is_google_embeddings_model($model))
                        {
                            $error = '';
                            $response = aiomatic_generate_embeddings_google($model, $content, $error);
                            if($response === false)
                            {
                                $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                return $aiomatic_result;
                            }
                            if(isset($response['error']))
                            {
                                $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                                return $aiomatic_result;
                            }
                            $embedding = $response;
                        }
                        else
                        {
                            if(aiomatic_is_aiomaticapi_key($this->api_key))
                            {
                                $error = '';
                                $response = aiomatic_embeddings_aiomaticapi($token, $model, $content, 0, $error);
                                if($response === false)
                                {
                                    $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                    return $aiomatic_result;
                                }
                                if(isset($response->error))
                                {
                                    $aiomatic_result['data'] = 'Error while processing AI response: ' . $response->error;
                                    return $aiomatic_result;
                                }
                                if(!isset($response[0]->embedding))
                                {
                                    $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . print_r($response, true);
                                    return $aiomatic_result;
                                }
                                apply_filters( 'aiomatic_ai_reply', $response, $query );
                                $embedding = $response[0]->embedding;
                            }
                            else
                            {
                                if (aiomatic_check_if_azure($aiomatic_Main_Settings)) 
                                {
                                    $error = '';
                                    $response = aiomatic_embeddings_azure($token, $model, $content, 0, $error);
                                    if($response === false)
                                    {
                                        $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                                        return $aiomatic_result;
                                    }
                                    else
                                    {
                                        $embedding = (array)$response[0]->embedding;
                                        apply_filters( 'aiomatic_ai_reply', $response, $query );
                                    }
                                }
                                else
                                {
                                    $response = $openai->embeddings(array(
                                        'input' => $content,
                                        'model' => $model
                                    ));
                                
                                    $response = json_decode($response, true);
                                    if(isset($response['error']) && !empty($response['error'])) {
                                        $aiomatic_result['msg'] = $response['error']['message'];
                                    }
                                    else{
                                        if(
                                            !isset($response['data'][0]['embedding'])
                                        )
                                        {
                                            $aiomatic_result['msg'] = 'Invalid embedding response';
                                            return $aiomatic_result;
                                        }
                                        $embedding = $response['data'][0]['embedding'];
                                        apply_filters( 'aiomatic_ai_reply', $response, $query );
                                    }
                                }
                            }
                        }
                    }
                    if(empty($embedding))
                    {
                        if($aiomatic_result['msg'] == 'Something went wrong with embeddings processing')
                        {
                            $aiomatic_result['msg'] = 'No data returned';
                        }
                    }
                    else
                    {
                        if(empty($namespace))
                        {
                            if (isset($aiomatic_Main_Settings['qdrant_name']) && trim($aiomatic_Main_Settings['qdrant_name']) != '')
                            {
                                $index_name = $aiomatic_Main_Settings['qdrant_name'];
                            }
                            else
                            {
                                $index_name = 'qdrant';
                            }
                        }
                        else
                        {
                            $index_name = trim($namespace);
                        }
                        try
                        {
                            require_once (dirname(__FILE__) . "/Qdrant.php");
                            $my_indexes = aimogenpro_qdrant_list_indexes($aiomatic_qdrant_api, $qdrant_url);
                            $found = false;
                            foreach($my_indexes as $mid)
                            {
                                if($mid['name'] == $index_name)
                                {
                                    $found = true;
                                }
                            }
                            if($found == false)
                            {
                                aimogenpro_qdrant_add_index($aiomatic_qdrant_api, $qdrant_url, $index_name);
                            }
                            if(!$embaddings_id) {
                                if(function_exists('mb_substr'))
                                {
                                    $embedding_title = empty($title) ? mb_substr($content, 0, 50, 'UTF-8') : $title;
                                }
                                else
                                {
                                    $embedding_title = empty($title) ? substr($content, 0, 50) : $title;
                                }
                                $embedding_data = array(
                                    'post_type' => 'aiomatic_embeddings',
                                    'post_title' => $embedding_title,
                                    'post_content' => $content,
                                    'post_status' => 'publish'
                                );
                                if (!empty($post_type)) {
                                    $embedding_data['post_type'] = $post_type;
                                }
                                remove_filter('content_save_pre', 'wp_filter_post_kses');
                                remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                $embaddings_id = wp_insert_post($embedding_data);
                                add_filter('content_save_pre', 'wp_filter_post_kses');
                                add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                            }
                            if(is_wp_error($embaddings_id))
                            {
                                $aiomatic_result['msg'] = $embaddings_id->get_error_message();
                            }
                            elseif($embaddings_id === 0)
                            {
                                $aiomatic_result['msg'] = 'Failed to insert embedding to database: ' . $embedding_title;
                            }
                            else 
                            {
                                if(empty($namespace))
                                {
                                    if (isset($aiomatic_Main_Settings['qdrant_name']) && trim($aiomatic_Main_Settings['qdrant_name']) != '')
                                    {
                                        update_post_meta($embaddings_id, 'aiomatic_namespace', trim($aiomatic_Main_Settings['qdrant_name']));
                                    }
                                }
                                else
                                {
                                    update_post_meta($embaddings_id, 'aiomatic_namespace', trim($namespace));
                                }
                                update_post_meta($embaddings_id, 'aiomatic_start',time());
                                if(aiomatic_is_aiomaticapi_key($this->api_key) || (aiomatic_check_if_azure($aiomatic_Main_Settings)))
                                {
                                    $usage_tokens = count(aiomatic_encode($content));
                                }
                                else
                                {
                                    if(isset($response['usage']['total_tokens']))
                                    {
                                        $usage_tokens = $response['usage']['total_tokens'];
                                    }
                                    else
                                    {
                                        $usage_tokens = count(aiomatic_encode($content));
                                    }
                                }
                                update_post_meta($embaddings_id, 'aiomatic_embedding_token', $usage_tokens);
                                update_post_meta($embaddings_id, 'aiomatic_embedding_model', $model);
                                $vector = array(
                                    'id' => (string)$embaddings_id,
                                    'values' => $embedding
                                );
                                $quadrant_id = aimogenpro_qdrant_add_vector( $aiomatic_qdrant_api, $qdrant_url, $index_name, $vector );
                                $aiomatic_result['status'] = 'success';
                                $aiomatic_result['id'] = $embaddings_id;
                                update_post_meta($embaddings_id, 'aiomatic_completed', time());
                                update_post_meta($embaddings_id, 'quadrant_id', $quadrant_id);
                            }
                        }
                        catch(Exception $e)
                        {
                            $aiomatic_result['msg'] = 'Qdrant exception: ' . $e->getMessage();
                            wp_delete_post($embaddings_id, true);
                        }
                    }
                }
                else
                {
                    $aiomatic_result['msg'] = 'Missing OpenAI API Settings';
                }
            }
            else
            {
                $aiomatic_result['msg'] = 'Unrecognized embeddings provider selected';
            }
            return $aiomatic_result;
        }
        public function aimogenpro_get_embedding_data($content, $model = AIMOGEN_DEFAULT_MODEL_EMBEDDING)
        {
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings saving');
            $embedding = '';
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if (!isset($aiomatic_Main_Settings['app_id']) || trim($aiomatic_Main_Settings['app_id']) == '') 
            {
                $aiomatic_result['msg'] = 'Missing API Setting';
                return $aiomatic_result;
            }
            else 
            {
                if (!isset($aiomatic_Main_Settings['api_selector']) || trim($aiomatic_Main_Settings['api_selector']) != 'azure') 
                {
                    if(!aiomatic_is_aiomaticapi_key($this->api_key))
                    {
                        $openai = new OpenAi($this->api_key);
                        if (isset($aiomatic_Main_Settings['api_selector']) && trim($aiomatic_Main_Settings['api_selector']) == 'custom' && isset($aiomatic_Main_Settings['custom_endpoint']) && trim($aiomatic_Main_Settings['custom_endpoint'], ' /') != '') 
                        {
                            $openai->setCustomURL(trim($aiomatic_Main_Settings['custom_endpoint'], ' /'));
                        }
                        if (isset($aiomatic_Main_Settings['openai_organization']) && $aiomatic_Main_Settings['openai_organization'] != '')
                        {
                            $openai->setORG($aiomatic_Main_Settings['openai_organization']);
                        }
                    }
                    else
                    {
                        $openai = true;
                    }
                }
                else
                {
                    $openai = true;
                }
            }
            $max_tokens = aimogenpro_get_max_input_tokens($model);
            $in_tokens = count(aiomatic_encode($content));
            if($in_tokens > $max_tokens)
            {
                $content = aiomatic_strip_to_token_count($content, aimogenpro_get_max_input_tokens($model), false);
            }
            $token = $this->api_key;
            $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
            if($openai)
            {
                $session = aiomatic_get_session_id();
                $maxResults = 1;
                $query = new Aiomatic_Query($content, 2048, $model, 0, '', 'saveembeddings', 'embeddings', $token, $session, $maxResults, '', '');
                if(aiomatic_is_ollama_embeddings_model($model))
                {
                    $error = '';
                    $response = aiomatic_generate_embeddings_ollama($model, $content, $error);
                    if($response === false)
                    {
                        $aiomatic_result['data'] = 'Failed to call Embeddings API: ' . $error;
                        return $aiomatic_result;
                    }
                    if(isset($response['error']))
                    {
                        $aiomatic_result['data'] = 'Error while processing AI response: ' . $response['error'];
                        return $aiomatic_result;
                    }
                    $embedding = $response;
                }
                else
                {
                    if(aiomatic_google_extension_is_google_embeddings_model($model))
                    {
                        $error = '';
                        $response = aiomatic_generate_embeddings_google($model, $content, $error);
                        if($response === false)
                        {
                            $aiomatic_result['msg'] = 'Failed to call Embeddings API: ' . $error;
                            return $aiomatic_result;
                        }
                        if(isset($response['error']))
                        {
                            $aiomatic_result['msg'] = 'Error while processing AI response: ' . $response['error'];
                            return $aiomatic_result;
                        }
                        $embedding = $response;
                    }
                    else
                    {
                        if(aiomatic_is_aiomaticapi_key($this->api_key))
                        {
                            $error = '';
                            $response = aiomatic_embeddings_aiomaticapi($token, $model, $content, 0, $error);
                            if($response === false)
                            {
                                $aiomatic_result['msg'] = 'Failed to call Embeddings API: ' . $error;
                                return $aiomatic_result;
                            }
                            if(isset($response->error))
                            {
                                $aiomatic_result['msg'] = 'Error while processing AI response: ' . $response->error;
                                return $aiomatic_result;
                            }
                            if(!isset($response[0]->embedding))
                            {
                                $aiomatic_result['msg'] = 'Failed to call Embeddings API: ' . print_r($response, true);
                                return $aiomatic_result;
                            }
                            apply_filters( 'aiomatic_ai_reply', $response, $query );
                            $embedding = $response[0]->embedding;
                        }
                        else
                        {
                            if (aiomatic_check_if_azure($aiomatic_Main_Settings)) 
                            {
                                $error = '';
                                $response = aiomatic_embeddings_azure($token, $model, $content, 0, $error);
                                if($response === false)
                                {
                                    $aiomatic_result['msg'] = 'Failed to call Embeddings API: ' . $error;
                                    return $aiomatic_result;
                                }
                                else
                                {
                                    $embedding = (array)$response[0]->embedding;
                                    apply_filters( 'aiomatic_ai_reply', $response, $query );
                                }
                            }
                            else
                            {
                                $response = $openai->embeddings(array(
                                    'input' => $content,
                                    'model' => $model
                                ));
                            
                                $response = json_decode($response, true);
                                if(isset($response['error']) && !empty($response['error'])) {
                                    $aiomatic_result['msg'] = $response['error']['message'];
                                }
                                else{
                                    if(
                                        !isset($response['data'][0]['embedding'])
                                    )
                                    {
                                        $aiomatic_result['msg'] = 'Invalid embedding response';
                                        return $aiomatic_result;
                                    }
                                    $embedding = $response['data'][0]['embedding'];
                                    apply_filters( 'aiomatic_ai_reply', $response, $query );
                                }
                            }
                        }
                    }
                }
                if(empty($embedding))
                {
                    if($aiomatic_result['msg'] == 'Something went wrong with embeddings processing')
                    {
                        $aiomatic_result['msg'] = 'No data returned';
                    }
                }
                else
                {
                    unset($aiomatic_result['msg']);
                    $aiomatic_result['data'] = $embedding;
                    $aiomatic_result['status'] = 'success';
                }
            }
            else
            {
                $aiomatic_result['msg'] = 'Missing OpenAI API Settings';
            }
            return $aiomatic_result;
        }
        public function aiomatic_delete_embedding($embaddings_id)
        {
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings deletion');
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if ((!isset($aiomatic_Main_Settings['embeddings_api']) || trim($aiomatic_Main_Settings['embeddings_api']) == '') || (isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'pinecone'))
            {
                if (!isset($aiomatic_Main_Settings['pinecone_app_id']) || trim($aiomatic_Main_Settings['pinecone_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['pinecone_index']) || trim($aiomatic_Main_Settings['pinecone_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $aiomatic_pinecone_api = trim($aiomatic_Main_Settings['pinecone_app_id']);
                    $aiomatic_pinecone_environment = preg_replace("(^https?:\/\/)", "", trim($aiomatic_Main_Settings['pinecone_index']));    
                    $pinecone_url = 'https://' . $aiomatic_pinecone_environment . '/vectors/delete';
                    $headers = array(
                        'Content-Type' => 'application/json',
                        'Api-Key' => $aiomatic_pinecone_api
                    );
                    $pinecone_ids = 'ids='. $embaddings_id;
                    try 
                    {
                        wp_remote_request('https://' . $aiomatic_pinecone_environment . '/vectors/delete?'.$pinecone_ids, array(
                            'method' => 'DELETE',
                            'headers' => $headers,
                            'timeout' => 60
                        ));
                        $response = wp_remote_post($pinecone_url, array(
                            'headers' => $headers,
                            'body' => json_encode(array('ids' => array($embaddings_id))),
                            'timeout' => 60
                        ));
                        if(is_wp_error($response)){
                            $aiomatic_result['msg'] = $response->get_error_message();
                            wp_delete_post($embaddings_id, true);
                        }
                        elseif(wp_remote_retrieve_response_code( $response ) != 200)
                        {
                            $aiomatic_result['msg'] = 'Invalid response from API: ' . wp_remote_retrieve_response_code( $response );
                            wp_delete_post($embaddings_id, true);
                        }
                        else
                        {
                            $aiomatic_result['status'] = 'success';
                            $aiomatic_result['id'] = $embaddings_id;
                            wp_delete_post($embaddings_id, true);
                        }
                    }
                    catch (\Exception $e){
                        $aiomatic_result['msg'] = 'Exception thrown: ' . $e->getMessage();
                        wp_delete_post($embaddings_id, true);
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'chroma')
            {
                if (isset($aiomatic_Main_Settings['chroma_name']) && trim($aiomatic_Main_Settings['chroma_name']) != '') 
                {
                    $index_name = trim($aiomatic_Main_Settings['chroma_name']);
                }
                else
                {
                    $index_name = 'chroma';
                }

                if (!isset($aiomatic_Main_Settings['chroma_app_id']) || trim($aiomatic_Main_Settings['chroma_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['chroma_index']) || trim($aiomatic_Main_Settings['chroma_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma URL in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    try
                    {
                        require_once (dirname(__FILE__) . "/Chroma.php");

                        $chroma_api_key = trim($aiomatic_Main_Settings['chroma_app_id']);
                        $chroma_url = aimogenpro_chroma_normalize_base_url($aiomatic_Main_Settings['chroma_index']);

                        if(isset($aiomatic_Main_Settings['chroma_tennant']) && trim($aiomatic_Main_Settings['chroma_tennant']) != '')
                        {
                            $chroma_tenant = trim($aiomatic_Main_Settings['chroma_tennant']);
                        }
                        elseif(isset($aiomatic_Main_Settings['chroma_tenant']) && trim($aiomatic_Main_Settings['chroma_tenant']) != '')
                        {
                            $chroma_tenant = trim($aiomatic_Main_Settings['chroma_tenant']);
                        }
                        else
                        {
                            $chroma_tenant = 'default_tenant';
                        }

                        if(isset($aiomatic_Main_Settings['chroma_database']) && trim($aiomatic_Main_Settings['chroma_database']) != '')
                        {
                            $chroma_database = trim($aiomatic_Main_Settings['chroma_database']);
                        }
                        else
                        {
                            $chroma_database = 'default_database';
                        }

                        $chroma_id = get_post_meta($embaddings_id, 'chroma_id', true);

                        if(empty($chroma_id))
                        {
                            $chroma_id = get_post_meta($embaddings_id, 'chroma_vector_id', true);
                        }

                        /*
                        * Compatibility fallback, only for older records saved while Chroma reused Qdrant meta.
                        */
                        if(empty($chroma_id))
                        {
                            $chroma_id = get_post_meta($embaddings_id, 'quadrant_id', true);
                        }

                        if(empty($chroma_id))
                        {
                            $aiomatic_result['msg'] = 'Chroma ID not found: ' . $embaddings_id;
                            wp_delete_post($embaddings_id, true);
                        }
                        else
                        {
                            $delete_result = aimogenpro_chroma_delete_vectors(
                                $chroma_api_key,
                                $chroma_url,
                                $chroma_tenant,
                                $chroma_database,
                                $index_name,
                                array(
                                    'ids' => array($chroma_id)
                                )
                            );

                            if(is_wp_error($delete_result))
                            {
                                throw new Exception($delete_result->get_error_message());
                            }

                            $aiomatic_result['status'] = 'success';
                            $aiomatic_result['id'] = $embaddings_id;

                            wp_delete_post($embaddings_id, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        $aiomatic_result['msg'] = 'Exception thrown: ' . $e->getMessage();
                        wp_delete_post($embaddings_id, true);
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'openai')
            {
                require_once (dirname(__FILE__) . "/aiomatic-assistants-api.php");
                if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
                {
                    $aiomatic_result['msg'] = 'You must add an OpenAI API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                else
                {
                    try
                    {
                        $token = $this->api_key;

                        $vector_store_id = get_post_meta($embaddings_id, 'openai_vector_store_id', true);

                        if(empty($vector_store_id))
                        {
                            $vector_store_id = get_post_meta($embaddings_id, 'aiomatic_namespace', true);
                        }

                        if(empty($vector_store_id) && isset($aiomatic_Main_Settings['openai_vector_store_id']) && trim($aiomatic_Main_Settings['openai_vector_store_id']) != '')
                        {
                            $vector_store_id = trim($aiomatic_Main_Settings['openai_vector_store_id']);
                        }

                        if(empty($vector_store_id) && isset($aiomatic_Main_Settings['openai_vector_store_ids']) && !empty($aiomatic_Main_Settings['openai_vector_store_ids']))
                        {
                            if(is_array($aiomatic_Main_Settings['openai_vector_store_ids']))
                            {
                                $vector_store_id = trim(reset($aiomatic_Main_Settings['openai_vector_store_ids']));
                            }
                            else
                            {
                                $tmp_vector_store_ids = array_map('trim', explode(',', $aiomatic_Main_Settings['openai_vector_store_ids']));
                                $tmp_vector_store_ids = array_values(array_filter($tmp_vector_store_ids));

                                if(!empty($tmp_vector_store_ids))
                                {
                                    $vector_store_id = $tmp_vector_store_ids[0];
                                }
                            }
                        }

                        $openai_file_id = get_post_meta($embaddings_id, 'openai_file_id', true);

                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'openai_vector_store_file_id', true);
                        }
                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'chroma_id', true);
                        }

                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'chroma_vector_id', true);
                        }

                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'quadrant_id', true);
                        }

                        if(empty($vector_store_id))
                        {
                            $aiomatic_result['msg'] = 'OpenAI Vector Store ID not found: ' . $embaddings_id;
                            wp_delete_post($embaddings_id, true);
                        }
                        elseif(empty($openai_file_id))
                        {
                            $aiomatic_result['msg'] = 'OpenAI file ID not found: ' . $embaddings_id;
                            wp_delete_post($embaddings_id, true);
                        }
                        else
                        {
                            try
                            {
                                aiomatic_openai_delete_vector_store_file(
                                    $token,
                                    $vector_store_id,
                                    $openai_file_id
                                );
                            }
                            catch(Exception $delete_e)
                            {
                                $aiomatic_result['msg'] = 'OpenAI remote delete warning: ' . $delete_e->getMessage();
                            }

                            $aiomatic_result['status'] = 'success';
                            $aiomatic_result['id'] = $embaddings_id;

                            wp_delete_post($embaddings_id, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        $aiomatic_result['msg'] = 'Exception thrown: ' . $e->getMessage();
                        wp_delete_post($embaddings_id, true);
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'qdrant')
            {
                if (isset($aiomatic_Main_Settings['qdrant_name']) && trim($aiomatic_Main_Settings['qdrant_name']) != '') 
                {
                    $index_name = $aiomatic_Main_Settings['qdrant_name'];
                }
                else
                {
                    $index_name = 'qdrant';
                }
                if (!isset($aiomatic_Main_Settings['qdrant_app_id']) || trim($aiomatic_Main_Settings['qdrant_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['qdrant_index']) || trim($aiomatic_Main_Settings['qdrant_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $aiomatic_qdrant_api = trim($aiomatic_Main_Settings['qdrant_app_id']);
                    $aiomatic_qdrant_environment = rtrim(trim($aiomatic_Main_Settings['qdrant_index'], '/'));
                    $aiomatic_qdrant_environment = preg_replace("(^https?:\/\/)", "", $aiomatic_qdrant_environment);
                    $qdrant_url = 'https://' . $aiomatic_qdrant_environment;

                    $quadrant_id = get_post_meta($embaddings_id, 'quadrant_id', true);
                    if(empty($quadrant_id))
                    {
                        $aiomatic_result['msg'] = 'Qdrant ID not found: ' . $embaddings_id;
                        wp_delete_post($embaddings_id, true);
                    }
                    else
                    {
                        try
                        {
                            require_once (dirname(__FILE__) . "/Qdrant.php");
                            aimogenpro_qdrant_delete_vectors( $aiomatic_qdrant_api, $qdrant_url, $index_name, array($quadrant_id) );
                            $aiomatic_result['status'] = 'success';
                            $aiomatic_result['id'] = $embaddings_id;
                            wp_delete_post($embaddings_id, true);
                        }
                        catch(Exception $e)
                        {
                            $aiomatic_result['msg'] = 'Exception thrown: ' . $e->getMessage();
                            wp_delete_post($embaddings_id, true);
                        }
                    }
                }
            }
            else
            {
                $aiomatic_result['msg'] = 'Unrecognized embeddings provider selected';
            }
            return $aiomatic_result;
        }
        public function aiomatic_delete_embeddings_ids($ids)
        {
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings ids');
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if ((!isset($aiomatic_Main_Settings['embeddings_api']) || trim($aiomatic_Main_Settings['embeddings_api']) == '') || (isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'pinecone'))
            {
                if (!isset($aiomatic_Main_Settings['pinecone_app_id']) || trim($aiomatic_Main_Settings['pinecone_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['pinecone_index']) || trim($aiomatic_Main_Settings['pinecone_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $aiomatic_pinecone_api = trim($aiomatic_Main_Settings['pinecone_app_id']);
                    $aiomatic_pinecone_environment = preg_replace("(^https?:\/\/)", "", trim($aiomatic_Main_Settings['pinecone_index']));   
                    try {
                        $headers = array(
                            'Content-Type' => 'application/json',
                            'Api-Key' => $aiomatic_pinecone_api
                        );
                        $pinecone_ids = [];
                        foreach($ids as $id)
                        {
                            $pinecone_ids[] = 'ids=' . intval($id);
                        }
                        $pinecone_ids = implode('&', $pinecone_ids);
                        $pinecone_ids = trim($pinecone_ids, '&');
                        $response = wp_remote_request('https://' . $aiomatic_pinecone_environment . '/vectors/delete?'.$pinecone_ids, array(
                            'method' => 'DELETE',
                            'headers' => $headers,
                            'timeout' => 60
                        ));
                        if(is_wp_error($response)){
                            $aiomatic_result['msg'] = $response->get_error_message();
                        }
                        elseif(wp_remote_retrieve_response_code( $response ) != 200)
                        {
                            $aiomatic_result['msg'] = 'Invalid response from API: ' . wp_remote_retrieve_response_code( $response );
                        }
                        else
                        {
                            $aiomatic_result['status'] = 'success';
                        }
                    }
                    catch (\Exception $exception){

                    }
                    foreach ($ids as $id){
                        wp_delete_post($id, true);
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'chroma')
            {
                if (isset($aiomatic_Main_Settings['chroma_name']) && trim($aiomatic_Main_Settings['chroma_name']) != '') 
                {
                    $index_name = trim($aiomatic_Main_Settings['chroma_name']);
                }
                else
                {
                    $index_name = 'chroma';
                }

                if (!isset($aiomatic_Main_Settings['chroma_app_id']) || trim($aiomatic_Main_Settings['chroma_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['chroma_index']) || trim($aiomatic_Main_Settings['chroma_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma URL in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    try
                    {
                        require_once (dirname(__FILE__) . "/Chroma.php");

                        $chroma_api_key = trim($aiomatic_Main_Settings['chroma_app_id']);
                        $chroma_url = aimogenpro_chroma_normalize_base_url($aiomatic_Main_Settings['chroma_index']);

                        if(isset($aiomatic_Main_Settings['chroma_tennant']) && trim($aiomatic_Main_Settings['chroma_tennant']) != '')
                        {
                            $chroma_tenant = trim($aiomatic_Main_Settings['chroma_tennant']);
                        }
                        elseif(isset($aiomatic_Main_Settings['chroma_tenant']) && trim($aiomatic_Main_Settings['chroma_tenant']) != '')
                        {
                            $chroma_tenant = trim($aiomatic_Main_Settings['chroma_tenant']);
                        }
                        else
                        {
                            $chroma_tenant = 'default_tenant';
                        }

                        if(isset($aiomatic_Main_Settings['chroma_database']) && trim($aiomatic_Main_Settings['chroma_database']) != '')
                        {
                            $chroma_database = trim($aiomatic_Main_Settings['chroma_database']);
                        }
                        else
                        {
                            $chroma_database = 'default_database';
                        }

                        $chroma_ids = array();

                        foreach ($ids as $embaddings_id)
                        {
                            $chroma_id = get_post_meta($embaddings_id, 'chroma_id', true);

                            if(empty($chroma_id))
                            {
                                $chroma_id = get_post_meta($embaddings_id, 'chroma_vector_id', true);
                            }

                            /*
                            * Compatibility fallback, only for older records saved while Chroma reused Qdrant meta.
                            */
                            if(empty($chroma_id))
                            {
                                $chroma_id = get_post_meta($embaddings_id, 'quadrant_id', true);
                            }

                            if(!empty($chroma_id))
                            {
                                $chroma_ids[] = $chroma_id;
                            }
                        }

                        $chroma_ids = array_values(array_unique(array_filter($chroma_ids)));

                        if(!empty($chroma_ids))
                        {
                            $delete_result = aimogenpro_chroma_delete_vectors(
                                $chroma_api_key,
                                $chroma_url,
                                $chroma_tenant,
                                $chroma_database,
                                $index_name,
                                array(
                                    'ids' => $chroma_ids
                                )
                            );

                            if(is_wp_error($delete_result))
                            {
                                throw new Exception($delete_result->get_error_message());
                            }
                        }

                        $aiomatic_result['status'] = 'success';
                    }
                    catch(Exception $e)
                    {
                        $aiomatic_result['msg'] = 'Exception thrown: ' . $e->getMessage();
                    }

                    foreach ($ids as $id)
                    {
                        wp_delete_post($id, true);
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'openai')
            {
                require_once (dirname(__FILE__) . "/res/aiomatic-assistants-api.php");

                if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
                {
                    $aiomatic_result['msg'] = 'You must add an OpenAI API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                else
                {
                    $token = $this->api_key;
                    $deleted_files = 0;
                    $delete_errors = array();

                    foreach ($ids as $embaddings_id)
                    {
                        $vector_store_id = get_post_meta($embaddings_id, 'openai_vector_store_id', true);

                        if(empty($vector_store_id))
                        {
                            $vector_store_id = get_post_meta($embaddings_id, 'aiomatic_namespace', true);
                        }

                        $openai_file_id = get_post_meta($embaddings_id, 'openai_file_id', true);

                        /*
                        * Compatibility fallback, only for records saved while old meta keys were reused.
                        */
                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'openai_vector_store_file_id', true);
                        }

                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'chroma_id', true);
                        }

                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'chroma_vector_id', true);
                        }

                        if(empty($openai_file_id))
                        {
                            $openai_file_id = get_post_meta($embaddings_id, 'quadrant_id', true);
                        }

                        if(!empty($vector_store_id) && !empty($openai_file_id))
                        {
                            try
                            {
                                aiomatic_openai_delete_vector_store_file(
                                    $token,
                                    $vector_store_id,
                                    $openai_file_id
                                );

                                $deleted_files++;
                            }
                            catch(Exception $e)
                            {
                                $delete_errors[] = '#' . $embaddings_id . ': ' . $e->getMessage();
                            }
                        }

                        wp_delete_post($embaddings_id, true);
                    }

                    $aiomatic_result['status'] = 'success';
                    $aiomatic_result['deleted_files'] = $deleted_files;

                    if(!empty($delete_errors))
                    {
                        $aiomatic_result['msg'] = 'Deleted local embeddings, but some OpenAI remote files could not be removed: ' . implode(' | ', $delete_errors);
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'qdrant')
            {
                if (isset($aiomatic_Main_Settings['qdrant_name']) && trim($aiomatic_Main_Settings['qdrant_name']) != '') 
                {
                    $index_name = $aiomatic_Main_Settings['qdrant_name'];
                }
                else
                {
                    $index_name = 'qdrant';
                }
                if (!isset($aiomatic_Main_Settings['qdrant_app_id']) || trim($aiomatic_Main_Settings['qdrant_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['qdrant_index']) || trim($aiomatic_Main_Settings['qdrant_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $aiomatic_qdrant_api = trim($aiomatic_Main_Settings['qdrant_app_id']);
                    $aiomatic_qdrant_environment = rtrim(trim($aiomatic_Main_Settings['qdrant_index'], '/'));
                    $aiomatic_qdrant_environment = preg_replace("(^https?:\/\/)", "", $aiomatic_qdrant_environment);
                    $qdrant_url = 'https://' . $aiomatic_qdrant_environment;
                    $quadrant_ids = array();
                    foreach ($ids as $embaddings_id){
                        $quadrant_id = get_post_meta($embaddings_id, 'quadrant_id', true);
                        if(!empty($quadrant_id))
                        {
                            $quadrant_ids[] = $quadrant_id;
                        }
                    }
                    try
                    {
                        if(!empty($quadrant_ids))
                        {
                            require_once (dirname(__FILE__) . "/Qdrant.php");
                            aimogenpro_qdrant_delete_vectors( $aiomatic_qdrant_api, $qdrant_url, $index_name, $quadrant_ids );
                        }
                        $aiomatic_result['status'] = 'success';
                    }
                    catch(Exception $e)
                    {
                        $aiomatic_result['msg'] = 'Exception thrown: ' . $e->getMessage();
                    }
                    foreach ($ids as $id)
                    {
                        wp_delete_post($id, true);
                    }
                }
            }
            else
            {
                $aiomatic_result['msg'] = 'Unrecognized embeddings provider selected';
            }
            return $aiomatic_result;
        }
        public function aiomatic_deleteall_embeddings()
        {
            global $wpdb;
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings general deletion');
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if ((!isset($aiomatic_Main_Settings['embeddings_api']) || trim($aiomatic_Main_Settings['embeddings_api']) == '') || (isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'pinecone'))
            {
                if (!isset($aiomatic_Main_Settings['pinecone_app_id']) || trim($aiomatic_Main_Settings['pinecone_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['pinecone_index']) || trim($aiomatic_Main_Settings['pinecone_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Pinecone index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $ids = $wpdb->get_results("SELECT ID FROM ".$wpdb->posts." WHERE post_type='aiomatic_embeddings'");
                    $ids = wp_list_pluck($ids,'ID');
                    if(count($ids)) {
                        $aiomatic_result = $this->aiomatic_delete_embeddings_ids($ids);
                    }
                    else
                    {
                        $aiomatic_result['msg'] = 'No embeddings found to delete!';
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'chroma')
            {
                if (!isset($aiomatic_Main_Settings['chroma_app_id']) || trim($aiomatic_Main_Settings['chroma_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['chroma_index']) || trim($aiomatic_Main_Settings['chroma_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma URL in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['chroma_name']) || trim($aiomatic_Main_Settings['chroma_name']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Chroma Collection Name in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $ids = $wpdb->get_results("SELECT ID FROM " . $wpdb->posts . " WHERE post_type='aiomatic_embeddings'");
                    $ids = wp_list_pluck($ids, 'ID');

                    if(count($ids)) 
                    {
                        $aiomatic_result = $this->aiomatic_delete_embeddings_ids($ids);
                    }
                    else
                    {
                        $aiomatic_result['msg'] = 'No embeddings found to delete!';
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'openai')
            {
                if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
                {
                    $aiomatic_result['msg'] = 'You must add an OpenAI API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                else
                {
                    $ids = $wpdb->get_results("SELECT ID FROM " . $wpdb->posts . " WHERE post_type='aiomatic_embeddings'");
                    $ids = wp_list_pluck($ids, 'ID');

                    if(count($ids)) 
                    {
                        $aiomatic_result = $this->aiomatic_delete_embeddings_ids($ids);
                    }
                    else
                    {
                        $aiomatic_result['msg'] = 'No embeddings found to delete!';
                    }
                }
            }
            elseif(isset($aiomatic_Main_Settings['embeddings_api']) && trim($aiomatic_Main_Settings['embeddings_api']) == 'qdrant')
            {
                if (!isset($aiomatic_Main_Settings['qdrant_app_id']) || trim($aiomatic_Main_Settings['qdrant_app_id']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant API key in the plugin\'s \'Settings\' menu (API Keys tab), before you can use this feature!';
                }
                elseif (!isset($aiomatic_Main_Settings['qdrant_index']) || trim($aiomatic_Main_Settings['qdrant_index']) == '') 
                {
                    $aiomatic_result['msg'] = 'You must add a Qdrant index in the plugin\'s \'Settings\' menu (Embeddings tab), before you can use this feature!';
                }
                else
                {
                    $ids = $wpdb->get_results("SELECT ID FROM ".$wpdb->posts." WHERE post_type='aiomatic_embeddings'");
                    $ids = wp_list_pluck($ids,'ID');
                    if(count($ids)) {
                        $aiomatic_result = $this->aiomatic_delete_embeddings_ids($ids);
                    }
                    else
                    {
                        $aiomatic_result['msg'] = 'No embeddings found to delete!';
                    }
                }
            }
            else
            {
                $aiomatic_result['msg'] = 'Unrecognized embeddings provider selected';
            }
            return $aiomatic_result;
        }

        public function aiomatic_embeddings()
        {
            if ( !wp_verify_nonce( $_POST['nonce'], 'aiomatic_embeddings' ) ) {
                wp_send_json_error(array( 'message' => 'Not allowed' ), 403);
            }
            if ( ! current_user_can('edit_posts') ) {
                wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
            }
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if (isset($aiomatic_Main_Settings['embeddings_model']) && $aiomatic_Main_Settings['embeddings_model'] != '') 
            {
                $model = $aiomatic_Main_Settings['embeddings_model'];
            }
            else
            {
                $model = AIMOGEN_DEFAULT_MODEL_EMBEDDING;
            }
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings processing');
            $namespace = '';
            if(isset($_POST['namespace']) && !empty($_POST['namespace']))
            {
                $namespace = sanitize_text_field(
                    wp_unslash($_POST['namespace'])
                );
            }
            if(isset($_POST['content']) && !empty($_POST['content']))
            {
                $content = wp_kses_post(strip_tags(wp_unslash($_POST['content'])));
                if(!empty($content)){
                    $aiomatic_result = $this->aimogenpro_save_embedding($content, '', '', false, $model, $namespace);
                }
                else 
                {
                    $aiomatic_result['msg'] = 'Please insert your content first!';
                }
            }
            wp_send_json($aiomatic_result);
        }
        public function aiomatic_delete_namespace_embeddings($namespace)
        {
            global $wpdb;

            $aiomatic_result = [
                'status' => 'error',
                'msg'    => 'No embeddings found for namespace'
            ];

            $namespace = trim($namespace);
            if (empty($namespace)) {
                $aiomatic_result['msg'] = 'Empty namespace provided';
                return $aiomatic_result;
            }

            $embedding_ids = $wpdb->get_col($wpdb->prepare("
                SELECT DISTINCT p.ID
                FROM {$wpdb->posts} p
                INNER JOIN {$wpdb->postmeta} pm 
                    ON p.ID = pm.post_id
                WHERE p.post_type = 'aiomatic_embeddings'
                AND pm.meta_key = 'aiomatic_namespace'
                AND pm.meta_value = %s
            ", $namespace));

            if (empty($embedding_ids)) {
                return $aiomatic_result;
            }

            $delete_result = $this->aiomatic_delete_embeddings_ids($embedding_ids);

            if (isset($delete_result['status']) && $delete_result['status'] === 'success') {
                return [
                    'status' => 'success',
                    'deleted' => count($embedding_ids)
                ];
            }

            return $delete_result;
        }
        public function aiomatic_delete_namespace_embeddings_nojson($namespace)
        {
            return $this->aiomatic_delete_namespace_embeddings($namespace);
        }
        public function aiomatic_create_single_embedding($embeddings_str, $namespace = '')
        {
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings creation');
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if (isset($aiomatic_Main_Settings['embeddings_model']) && $aiomatic_Main_Settings['embeddings_model'] != '') 
            {
                $model = $aiomatic_Main_Settings['embeddings_model'];
            }
            else
            {
                $model = AIMOGEN_DEFAULT_MODEL_EMBEDDING;
            }
            $content = wp_kses_post(strip_tags($embeddings_str));
            if(!empty($content)){
                $aiomatic_result = $this->aimogenpro_save_embedding($content, '', '', false, $model, $namespace);
            }
            wp_send_json($aiomatic_result);
        }
        public function aiomatic_create_single_embedding_nojson($embeddings_str, $namespace = '')
        {
            $aiomatic_result = array('status' => 'error', 'msg' => 'Something went wrong with embeddings nojson creation');
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if (isset($aiomatic_Main_Settings['embeddings_model']) && $aiomatic_Main_Settings['embeddings_model'] != '') 
            {
                $model = $aiomatic_Main_Settings['embeddings_model'];
            }
            else
            {
                $model = AIMOGEN_DEFAULT_MODEL_EMBEDDING;
            }
            $content = wp_kses_post(strip_tags($embeddings_str));
            if(!empty($content)){
                $aiomatic_result = $this->aimogenpro_save_embedding($content, '', '', false, $model, $namespace);
            }
            return $aiomatic_result;
        }
        public function aiomatic_create_embeddings($embeddings_str, $namespace = '')
        {
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            if (isset($aiomatic_Main_Settings['embeddings_model']) && $aiomatic_Main_Settings['embeddings_model'] != '') 
            {
                $model = $aiomatic_Main_Settings['embeddings_model'];
            }
            else
            {
                $model = AIMOGEN_DEFAULT_MODEL_EMBEDDING;
            }
            $aiomatic_result = array('status' => 'error', 'msg' => 'No embeddings could be saved');
            $embeddings_str_arr = preg_split('/\r\n|\r|\n/', $embeddings_str);
            foreach($embeddings_str_arr as $embedme)
            {
                $content = wp_kses_post(strip_tags($embedme));
                if(!empty($content)){
                    $aiomatic_result = $this->aimogenpro_save_embedding($content, '', '', false, $model, $namespace);
                }
            }
            wp_send_json($aiomatic_result);
        }
    }
}
