<?php

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

class ASSI_Ajax_POST {

    static private $instance = null;

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

    public function __construct() {
        add_action('wp_ajax_assi_auth_save', array($this, 'authSave'));
        add_action('wp_ajax_assi_auth_remove', array($this, 'authRemove'));
        add_action('wp_ajax_assi_get_templates', array($this, 'getTemplates'));
        add_action('wp_ajax_assi_save_template', array($this, 'saveTemplate'));
        add_action('wp_ajax_assi_delete_template', array($this, 'deleteTemplate'));
        add_action('wp_ajax_assi_edit_template', array($this, 'editTemplate'));
        add_action('wp_ajax_assi_get_chat_list', array($this, 'getChatList'));
        add_action('wp_ajax_assi_get_chat_history', array($this, 'getChatHistory'));
        add_action('wp_ajax_assi_chat_send_prompt', array($this, 'chatSendPrompt'));
        add_action('wp_ajax_assi_chat_delete', array($this, 'chatDelete'));
        add_action('wp_ajax_assi_chat_save_msg_as_draft', array($this, 'chatSaveMsgAsDraft'));
        add_action('wp_ajax_assi_get_dashboard_activity', array($this, 'getDashboardActivity'));
        add_action('wp_ajax_assi_submit_support_ticket', array($this, 'submitSupportTicket'));
        add_action('wp_ajax_assi_chat_start_expert_mode', array($this, 'chatStartExpertMode'));
        add_action('wp_ajax_assi_check_open_notifications', array($this, 'checkOpenNotifications'));
        add_action('wp_ajax_assi_notification_delete', array($this, 'notificationDelete'));
        add_action('wp_ajax_assi_settings_get', array($this, 'settingsGet'));
        add_action('wp_ajax_assi_settings_save', array($this, 'settingsSave'));
        add_action('wp_ajax_assi_update_credits_left', array($this, 'updateCreditsLeft'));
        add_action('wp_ajax_assi_update_credits_total', array($this, 'updateCreditsTotal'));
        add_action('wp_ajax_assi_update_max_chats', array($this, 'updateMaxChats'));
        add_action('wp_ajax_assi_update_max_templates', array($this, 'updateMaxTemplates'));
        add_action('wp_ajax_assi_update_plan_id', array($this, 'updatePlanId'));
        add_action('wp_ajax_assi_modal_onboarding_close', array($this, 'modalOnboardingClose'));
        add_action('wp_ajax_assi_editor_send_prompt', array($this, 'editorSendPrompt'));
        add_action('wp_ajax_assi_editor_inline_send_prompt', array($this, 'editorInlineSendPrompt'));
	    add_action('wp_ajax_assi_settings_consent_save', array($this, 'settingsConsentSave'));
	    add_action('wp_ajax_assi_editor_post_get_focus_keyword', array($this, 'getPostFocusKeyword'));
	    add_action('wp_ajax_assi_open_ai_status', array($this, 'checkOpenAiStatus'));
	    add_action('wp_ajax_assi_chat_change_name', array($this, 'chatChangeName'));
	    add_action('wp_ajax_assi_get_blog_posts', array($this, 'getBlogPosts'));
        add_action('wp_ajax_assi_editor_send_prompt_image', array($this, 'editorSendPromptImage'));
        add_action('wp_ajax_assi_upload_image_to_library', array($this, 'uploadImageToLibrary'));
        add_action('wp_ajax_assi_upload_audio_to_library', array($this, 'uploadAudioToLibrary'));
        add_action('wp_ajax_assi_settings_custom_ai_verify', array($this, 'settingsCustomAiVerify'));
        add_action('wp_ajax_assi_settings_custom_ai_save', array($this, 'settingsCustomAiSave'));
        add_action('wp_ajax_assi_settings_custom_ai_remove', array($this, 'settingsCustomAiRemove'));
        add_action('wp_ajax_assi_settings_custom_ai_change_status', array($this, 'settingsCustomAiChangeStatus'));
        add_action('wp_ajax_assi_template_assistant_create', array($this, 'templateAssistantCreate'));
        add_action('wp_ajax_assi_template_analyze_prompt', array($this, 'templateAnalyzePrompt'));
        add_action('wp_ajax_assi_template_assistant_create_structure', array($this, 'templateAssistantCreateStructure'));
        add_action('wp_ajax_assi_save_custom_style', array($this, 'saveCustomStyle'));
        add_action('wp_ajax_assi_delete_custom_style', array($this, 'deleteCustomStyle'));
        add_action('wp_ajax_assi_global_alert_delete', array($this, 'globalAlertDelete'));
        add_action('wp_ajax_assi_get_editor_notifications', array($this, 'getEditorNotifications'));
        add_action('wp_ajax_assi_delete_notification', array($this, 'deleteNotification'));
        add_action('wp_ajax_assi_editor_send_prompt_audio', array($this, 'editorSendPromptAudio'));
        add_action('wp_ajax_assi_create_notification', array($this, 'createNotification'));
        add_action('wp_ajax_assi_get_editor_history', array($this, 'getEditorHistory'));
        add_action('wp_ajax_assi_delete_history', array($this, 'deleteHistory'));
    }

    // SECTION: OAuth
    public function authSave() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $optionData = array(
            'plan' => array(
                'plan_id' => (isset($_POST['user_data']['ass_plan_id']) && (int) $_POST['user_data']['ass_plan_id'] > 0 ? (int) $_POST['user_data']['ass_plan_id'] : 1),
                'credits_open' => (isset($_POST['user_data']['ass_words_open']) ? (int) $_POST['user_data']['ass_words_open'] : 0),
                'credits_total' => (isset($_POST['user_data']['ass_words_total']) ? (int) $_POST['user_data']['ass_words_total'] : 0),
                'max_chats' => (isset($_POST['user_data']['ass_plan_max_count_chats']) ? (int) $_POST['user_data']['ass_plan_max_count_chats'] : 0),
                'max_templates' => (isset($_POST['user_data']['ass_plan_max_count_template']) ? (int) $_POST['user_data']['ass_plan_max_count_template'] : 0),
                'display_name' => (isset($_POST['display_name']) && !empty($_POST['display_name']) ? sanitize_text_field(wp_unslash($_POST['display_name'])) : ''),
                'first_name' => (isset($_POST['first_name']) && !empty($_POST['first_name']) ? sanitize_text_field(wp_unslash($_POST['first_name'])) : ''),
                'last_name' => (isset($_POST['last_name']) && !empty($_POST['last_name']) ? sanitize_text_field(wp_unslash($_POST['last_name'])) : ''),
                'registered' => true,
                'bonus_available' => false,
                'addons' => array(
                    'normal' => array(
                        'credits_open' => (isset($_POST['user_data']['ass_addon_quota']['normal']['open_quota']) ? (int) $_POST['user_data']['ass_addon_quota']['normal']['open_quota'] : 0),
                        'credits_total' => (isset($_POST['user_data']['ass_addon_quota']['normal']['max_quota']) ? (int) $_POST['user_data']['ass_addon_quota']['normal']['max_quota'] : 0),
                    ),
                    'promotion' => array(
                        'credits_open' => (isset($_POST['user_data']['ass_addon_quota']['promotion']['open_quota']) ? (int) $_POST['user_data']['ass_addon_quota']['promotion']['open_quota'] : 0),
                        'credits_total' => (isset($_POST['user_data']['ass_addon_quota']['promotion']['max_quota']) ? (int) $_POST['user_data']['ass_addon_quota']['promotion']['max_quota'] : 0),
                    )
                )
            )
        );
        update_option('ASSI_PLUGIN_ACCOUNT', $optionData, false);
        $globalAlerts = get_option('ASSI_PLUGIN_GLOBAL_ALERTS');
        if (isset($globalAlerts) && is_array($globalAlerts) && isset($globalAlerts['lost_connection'])) {
            unset($globalAlerts['lost_connection']);
            update_option('ASSI_PLUGIN_GLOBAL_ALERTS', $globalAlerts, false);
        }
        echo wp_json_encode(array('result' => true));
        wp_die();
    }

    public function authRemove() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'oauth/remove', array('blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN));
        if (isset($result->status) && $result->status == 'success') {
            delete_option('ASSI_PLUGIN_ACCOUNT');
            if (isset($result->user_data) && !empty($result->user_data)) {
                $this->updatePlanDetails($result->user_data, true);
            }
            echo wp_json_encode(array('result' => true));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            $error = sanitize_text_field(wp_unslash($result->message));
            echo wp_json_encode(array('result' => false, 'error' => $error, 'error_message' => ASSI_Tools::getErrorTranslation($error)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    // SECTION: Templates
    public function getTemplates() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN
        );

        if (isset($_POST['page']) && (int) $_POST['page'] > 0) {
            $data['page'] = (int) $_POST['page'];
        }

        $templateData = array();
        $userData = array();
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'custom/prompt/get', $data);
        if (isset($result->status) && $result->status == 'success' && isset($result->custom_prompts)) {
            if (isset($result->user_data) && !empty($result->user_data)) {
                $userData = $this->convertUserData($result->user_data);
                $this->updatePlanDetails($result->user_data);
            }
            foreach ($result->custom_prompts as $prompt) {
                $translations = array();
                $id = (isset($prompt->id) && !empty($prompt->id) ? (int) $prompt->id : 0);
                $name = (isset($prompt->prompt_name) && !empty($prompt->prompt_name) ? sanitize_text_field(wp_unslash($prompt->prompt_name)) : '');
                $text = (isset($prompt->custom_prompt->prompt) && !empty($prompt->custom_prompt->prompt) ? sanitize_textarea_field(wp_unslash($prompt->custom_prompt->prompt)) : '');
                $reference = (isset($prompt->custom_prompt->reference_text) && !empty($prompt->custom_prompt->reference_text) ? sanitize_textarea_field(wp_unslash($prompt->custom_prompt->reference_text)) : '');
                $language = (isset($prompt->custom_prompt->prompt_language) && !empty($prompt->custom_prompt->prompt_language) ? sanitize_text_field(wp_unslash($prompt->custom_prompt->prompt_language)) : '');
                $tone = (isset($prompt->custom_prompt->tone) && !empty($prompt->custom_prompt->tone) ? sanitize_text_field(wp_unslash($prompt->custom_prompt->tone)) : '');
                $pointOfView = (isset($prompt->custom_prompt->point_of_view) && !empty($prompt->custom_prompt->point_of_view) ? sanitize_text_field(wp_unslash($prompt->custom_prompt->point_of_view)) : '');
                $contentLength = (isset($prompt->custom_prompt->content_length) && !empty($prompt->custom_prompt->content_length) ? sanitize_text_field(wp_unslash($prompt->custom_prompt->content_length)) : '');
                $isSystem = (isset($prompt->is_system) ? (int) $prompt->is_system : 0);
                $showControls = (isset($prompt->options->show_options) && (int) $prompt->options->show_options == 1 ? true : false);
                $disabled = (isset($prompt->disabled) && (int) $prompt->disabled == 1 ? true : false);
                $planVersion = (isset($prompt->plan_version) && (int) $prompt->plan_version > 0 ? (int) $prompt->plan_version : 1);
                $category = (isset($prompt->category) && !empty($prompt->category) ? sanitize_text_field(wp_unslash($prompt->category)) : '');
                
                // editor relevant
                $type = (isset($prompt->type) && !empty($prompt->type) ? sanitize_text_field(wp_unslash($prompt->type)) : '');
                $optionFields = (isset($prompt->options->option_fields) && !empty($prompt->options->option_fields) ? $prompt->options->option_fields : array());
                $optionRequired = (isset($prompt->options->required) && !empty($prompt->options->required) ? $prompt->options->required : array());
                $optionModels = (isset($prompt->options->models) && !empty($prompt->options->models) ? $prompt->options->models : array());
                if (is_array($optionFields) && !empty($optionFields)) {
                    foreach ($optionFields as $i => $field) {
                        $optionFields[$i] = sanitize_text_field(wp_unslash($field));
                    }
                }
    
                if ($isSystem == 1) {
                    $translations = ASSI_Tools::getSystemTemplateTranslation((int) $id);
                    if (isset($translations['header']) && !empty($translations['header'])) {
                        $name = sanitize_text_field(wp_unslash($translations['header']));
                    }
                    if (isset($translations['info']) && !empty($translations['info'])) {
                        $text = sanitize_textarea_field(wp_unslash($translations['info']));
                    }
                }
    
                $templateData[] = array(
                    'id' => $id,
                    'header' => $name,
                    'text' => $text,
                    'reference' => $reference,
                    'language' => $language,
                    'tone' => $tone,
                    'point_of_view' => $pointOfView,
                    'content_length' => $contentLength,
                    'is_system' => $isSystem,
                    'show_controls' => $showControls,
                    'disabled' => $disabled,
                    'type' => $type,
                    'category' => $category,
                    'option_fields' => $optionFields,
                    'option_required' => $optionRequired,
                    'option_models' => $optionModels,
                    'plan_version' => $planVersion,
                    'plan_version_badge' => ASSI_Tools::getPlanName($planVersion)
                );
            }
        }

        global $wpdb;
        if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $dbResult = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_templates` WHERE `blog_user_id` = %d OR blog_access = 1", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)));
        } else {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $dbResult = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_templates` WHERE `blog_user_id` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)));
        }

        if (is_array($dbResult) && !empty($dbResult)) {
            foreach ($dbResult as $template) {
                $customPromptData = (isset($template->custom_prompt) && !empty($template->custom_prompt) ? json_decode($template->custom_prompt) : array());
                
                $id = (isset($template->id) && !empty($template->id) ? (int) $template->id : 0);
                $name = (isset($template->prompt_name) && !empty($template->prompt_name) ? sanitize_text_field(wp_unslash($template->prompt_name)) : '');
                $text = (isset($customPromptData->prompt) && !empty($customPromptData->prompt) ? sanitize_textarea_field(wp_unslash($customPromptData->prompt)) : '');
                $reference = (isset($customPromptData->reference_text) && !empty($customPromptData->reference_text) ? sanitize_textarea_field(wp_unslash($customPromptData->reference_text)) : '');
                $language = (isset($customPromptData->prompt_language) && !empty($customPromptData->prompt_language) ? sanitize_text_field(wp_unslash($customPromptData->prompt_language)) : '');
                $tone = (isset($customPromptData->tone) && !empty($customPromptData->tone) ? sanitize_text_field(wp_unslash($customPromptData->tone)) : '');
                $pointOfView = (isset($customPromptData->point_of_view) && !empty($customPromptData->point_of_view) ? sanitize_text_field(wp_unslash($customPromptData->point_of_view)) : '');
                $contentLength = (isset($customPromptData->content_length) && !empty($customPromptData->content_length) ? sanitize_text_field(wp_unslash($customPromptData->content_length)) : '');
                $isSystem = 0;
                $showControls = true;
                $disabled = false;
    
                $templateItem = array(
                    'id' => $id,
                    'header' => $name,
                    'text' => $text,
                    'reference' => $reference,
                    'language' => $language,
                    'tone' => $tone,
                    'point_of_view' => $pointOfView,
                    'content_length' => $contentLength,
                    'is_system' => $isSystem,
                    'show_controls' => $showControls,
                    'disabled' => $disabled,
                    'type' => 'user',
                    'option_fields' => array('post_content', 'content', 'point_of_view', 'tone', 'prompt_language'),
                    'option_required' => array('content', 'point_of_view', 'tone', 'prompt_language'),
                    'plan_version' => 1,
                    'plan_version_badge' => ASSI_Tools::getPlanName($planVersion),
                    'category' => 'text'
                );
                if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1 && isset($template->blog_user_id) && isset($template->blog_access) && (int) $template->blog_access == 1) {
                    if ((int) $template->blog_user_id != (int) ASSI_PLUGIN_BLOG_USER_ID) {
                        $userInfo = get_userdata((int) $template->blog_user_id);
                        if (isset($userInfo->display_name)) {
                            $templateItem['blog_access_owner_display_name'] = sanitize_text_field(wp_unslash($userInfo->display_name));
                        } else {
                            $templateItem['blog_access_owner_display_name'] = '';
                        }
                        $templateItem['blog_access_owner_id'] = (int) $template->blog_user_id;
                        $templateItem['blog_access'] = true;
                    } else {
                        $templateItem['blog_access_owner_id'] = 0;
                        $templateItem['blog_access'] = true;
                    }
                } else {
                    $templateItem['blog_access'] = false;
                }
                $templateData[] = $templateItem;
            }
        }

        if (isset($_POST['type']) && $_POST['type'] == 'select') {
            $html = '<option selected value>' . esc_html__('Select Template', 'assistini') . '</option>';
            $maxItems = 0;
            foreach ($templateData as $template) {
                if ($template['is_system'] != 1 && $template['disabled'] == false) {
                    $maxItems++;
                    $html .= '<option value="' . esc_attr($template['id']) . '" data-text="' . esc_attr($template['text']) . '" data-reference="' . esc_attr($template['reference']) . '" data-language="' . esc_attr($template['language']) . '" data-tone="' . esc_attr($template['tone']) . '" data-pov="' . esc_attr($template['point_of_view']) . '" data-length="' . esc_attr($template['content_length']) . '">' . esc_html($template['header']) . '</option>';
                }
            }

            echo wp_json_encode(array('result' => true, 'template_data' => $templateData, 'user_data' => $userData, 'html' => $html, 'count_templates' => $maxItems, 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
            wp_die();
        }
        $userTemplateCount = 0;
        foreach ($templateData as $template) {
            if ($template['is_system'] != 1 && $template['disabled'] == false) {
                $userTemplateCount++;
            }
        }
        echo wp_json_encode(array('result' => true, 'template_data' => $templateData, 'user_data' => $userData, 'user_template_count' => $userTemplateCount, 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
        wp_die();
    }

    public function saveTemplate() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['name']) || empty($_POST['name'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        if (!isset($_POST['prompt']) || empty($_POST['prompt'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_prompt', 'error_message' => ASSI_Tools::getErrorTranslation('missing_prompt')));
            wp_die();
        }

        $name = sanitize_text_field(wp_unslash($_POST['name']));
        $prompt = sanitize_textarea_field(wp_unslash($_POST['prompt']));
        $reference = (isset($_POST['reference_text']) && !empty($_POST['reference_text']) ? sanitize_textarea_field(wp_unslash($_POST['reference_text'])) : '');
        $language = (isset($_POST['language']) && !empty($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'en_US');
        $tone = (isset($_POST['tone']) && !empty($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : '');
        $view = (isset($_POST['view']) && !empty($_POST['view']) ? sanitize_text_field(wp_unslash($_POST['view'])) : '');
        $contentLength = (isset($_POST['content_length']) && !empty($_POST['content_length']) ? sanitize_text_field(wp_unslash($_POST['content_length'])) : '');
        $blogAccess = (isset($_POST['blog_access']) && (bool) $_POST['blog_access'] == true ? 1 : 0);
        $customPromptData = array(
            'prompt' => $prompt,
            'reference_text' => $reference,
            'prompt_language' => $language,
            'point_of_view' => $view,
            'tone' => $tone,
            'content_length' => $contentLength
        );
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->query($wpdb->prepare("INSERT INTO `{$wpdb->prefix}assi_user_templates` (`blog_user_id`, `create_date`, `last_mod_date`, `prompt_name`, `custom_prompt`, `blog_access`) VALUES (%d,%s,%s,%s,%s,%d);",
            (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0),
            gmdate('Y-m-d H:i:s'),
            gmdate('Y-m-d H:i:s'),
            $name,
            wp_json_encode($customPromptData),
            $blogAccess,
        ));
        if ($result) {
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function editTemplate() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['id']) || (int) $_POST['id'] <= 0 || !isset($_POST['name']) || empty($_POST['name'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        if (!isset($_POST['prompt']) || empty($_POST['prompt'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_prompt', 'error_message' => ASSI_Tools::getErrorTranslation('missing_prompt')));
            wp_die();
        }
        $name = sanitize_text_field(wp_unslash($_POST['name']));
        $prompt = sanitize_textarea_field(wp_unslash($_POST['prompt']));
        $reference = (isset($_POST['reference_text']) && !empty($_POST['reference_text']) ? sanitize_textarea_field(wp_unslash($_POST['reference_text'])) : '');
        $language = (isset($_POST['language']) && !empty($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'en_US');
        $tone = (isset($_POST['tone']) && !empty($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : '');
        $view = (isset($_POST['view']) && !empty($_POST['view']) ? sanitize_text_field(wp_unslash($_POST['view'])) : '');
        $contentLength = (isset($_POST['content_length']) && !empty($_POST['content_length']) ? sanitize_text_field(wp_unslash($_POST['content_length'])) : '');
        $blogAccess = (isset($_POST['blog_access']) && (bool) $_POST['blog_access'] == true ? 1 : 0);
        $customPromptData = array(
            'prompt' => $prompt,
            'reference_text' => $reference,
            'prompt_language' => $language,
            'point_of_view' => $view,
            'tone' => $tone,
            'content_length' => $contentLength
        );
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->query(
            $wpdb->prepare(
                "UPDATE `{$wpdb->prefix}assi_user_templates` SET `last_mod_date` = %s, `prompt_name` = %s, `custom_prompt` = %s, `blog_access` = %d WHERE `id` = %d AND `blog_user_id` = %d",
                gmdate('Y-m-d H:i:s'),
                $name,
                wp_json_encode($customPromptData),
                $blogAccess,
                (int) $_POST['id'],
                (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)
            )
        );
        if ($result) {
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function deleteTemplate() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }

        if (!isset($_POST['template_id']) || (int) $_POST['template_id'] <= 0) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM `{$wpdb->prefix}assi_user_templates` WHERE `id` = %d AND `blog_user_id` = %d",
                (int) $_POST['template_id'],
                (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)
            )
        );
        if ($result) {
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    // SECTION: Chat
    public function getChatList() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }   
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'sort_field' => 1
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'chat/session/get/list', $data);
        if ($result == 'connection_disabled_by_admin' || $result == 'client_blocked' || $result == 'server_blocked' || $result == 'server_auth_failed') {
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result)), 'error_message' => ASSI_Tools::getErrorTranslation($result)));
            wp_die();
        }
        if (!isset($result->status) || $result->status != 'success' || !isset($result->chat_sessions) || !is_array($result->chat_sessions)) {
            if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
                $error = sanitize_text_field(wp_unslash($result->message));
                echo wp_json_encode(array('result' => false, 'error' => $error, 'error_message' => ASSI_Tools::getErrorTranslation($error)));
                wp_die();
            }
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        if (isset($result->user_data)) {
            $this->updatePlanDetails($result->user_data);
        }
        $chatListHtml = '';
        foreach ($result->chat_sessions as $index => $chat) {
            $chatListHtml .= '<div class="ass-chat-list-item' . (isset($chat->disabled) && (int) $chat->disabled == 1 ? ' ass-chat-list-item-disabled' : '') . ' d-flex align-items-center mb-1" data-session-id="' . esc_attr($chat->session_id) . '" data-chat-name="' . esc_attr($chat->chat_name) . '" data-mode="' . esc_attr($chat->mode) . '" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="' . ($chat->mode == 0 && $chat->chat_name == '' ? esc_attr__('Chat', 'assistini') : esc_html($chat->chat_name)) . '">';
            $chatListHtml .= '<div class="' . (isset($chat->disabled) && (int) $chat->disabled == 0 ? 'ass-chat-sidebar-clickable ' : 'ass-chat-sidebar-clickable-disabled ') . 'flex-shrink-0">';
            $chatListHtml .= '<i class="bi bi-chat ass-size-32"></i>';
            $chatListHtml .= '</div>';
            $chatListHtml .= '<div class="' . (isset($chat->disabled) && (int) $chat->disabled == 0 ? 'ass-chat-sidebar-clickable ' : 'ass-chat-sidebar-clickable-disabled ') . 'ass-chat-sidebar-toggle flex-grow-1 text-truncate px-3">';
            $chatListHtml .= '<h3 class="ass-chat-list-item-name mb-0 text-truncate">' . ($chat->mode == 0 && $chat->chat_name == '' ? esc_html__('Chat', 'assistini') : esc_html($chat->chat_name)) . '</h3>';
            $chatListHtml .= '</div>';
            $chatListHtml .= '<div class="ass-chat-sidebar-delete ass-chat-sidebar-toggle flex-shrink-0">';
            $chatListHtml .= ' <button type="button" class="btn p-0 border-0 bg-transparent">';
            $chatListHtml .= '<i class="bi bi-trash"></i>';
            $chatListHtml .= '</button>';
            $chatListHtml .= '</div>';
            $chatListHtml .= '</div>';
        }
        echo wp_json_encode(array('result' => true, 'chat_list_html' => $chatListHtml, 'chat_sessions' => $result->chat_sessions, 'count_chats' => count($result->chat_sessions), 'user_data' => $this->convertUserData($result->user_data), 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
        wp_die();
    }

    public function getChatHistory() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['session_id']) || empty($_POST['session_id'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'session_id' => sanitize_text_field(wp_unslash($_POST['session_id']))
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'chat/session/get/content', $data);
        if (isset($result->status) && $result->status == 'success' && isset($result->chat_content) && !empty($result->chat_content)) {
            echo wp_json_encode(array('result' => true, 'chat_content' => $result->chat_content));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            $error = sanitize_text_field(wp_unslash($result->message));
            echo wp_json_encode(array('result' => false, 'error' => $error, 'error_message' => ASSI_Tools::getErrorTranslation($error)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function chatSendPrompt() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['user_prompt']) || empty($_POST['user_prompt'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_prompt', 'error_message' => ASSI_Tools::getErrorTranslation('missing_prompt')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'user_input' => sanitize_textarea_field(wp_unslash($_POST['user_prompt'])),
            'user_template_id' => (isset($_POST['user_template_id']) && (int) $_POST['user_template_id'] > 0 ? (int) $_POST['user_template_id'] : 0),
            'prompt_language' => (isset($_POST['user_lang']) && !empty($_POST['user_lang']) ? sanitize_text_field(wp_unslash($_POST['user_lang'])) : 'en_US'),
            'tone' => (isset($_POST['user_tone']) && !empty($_POST['user_tone']) ? sanitize_text_field(wp_unslash($_POST['user_tone'])) : ''),
            'point_of_view' => (isset($_POST['user_point_of_view']) && !empty($_POST['user_point_of_view']) ? sanitize_text_field(wp_unslash($_POST['user_point_of_view'])) : ''),
            'content_length' => (isset($_POST['user_content_length']) && !empty($_POST['user_content_length']) ? sanitize_text_field(wp_unslash($_POST['user_content_length'])) : ''),
        );

        if (isset($_POST['user_template_id']) && (int) $_POST['user_template_id'] > 0) {
            global $wpdb;
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $dbResult = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_templates` WHERE (`blog_user_id` = %d OR `blog_access` = 1) AND `id` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0), (int) $_POST['user_template_id']));
            } else {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $dbResult = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_templates` WHERE `blog_user_id` = %d AND `id` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0), (int) $_POST['user_template_id']));
            }
            if (is_object($dbResult) && !empty($dbResult) && isset($dbResult->custom_prompt) && !empty($dbResult->custom_prompt)) {
                $dbResult->custom_prompt = json_decode($dbResult->custom_prompt);
                if (isset($dbResult->custom_prompt->prompt) && !empty($dbResult->custom_prompt->prompt)) {
                    $data['user_input_textfield'] = $data['user_input'];
                    $data['user_input'] = sanitize_textarea_field(wp_unslash($dbResult->custom_prompt->prompt));
                }
                if (isset($dbResult->custom_prompt->reference_text) && !empty($dbResult->custom_prompt->reference_text)) {
                    $data['reference_text'] = sanitize_textarea_field(wp_unslash($dbResult->custom_prompt->reference_text));
                }
            }
        }
        if (isset($_POST['session_id']) && !empty($_POST['session_id'])) {
            $data['session_id'] = sanitize_text_field(wp_unslash($_POST['session_id']));
        }
        $requestId = ASSI_Tools::createRequestId();
        $data['request_id'] = $requestId;

        $endpoint = 'chat/create';
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . $endpoint, $data, 90);
        if ($result == 'client_timeout') {
            $localSessionId = (isset($_POST['local_session_id']) && !empty($_POST['local_session_id']) ? sanitize_text_field(wp_unslash($_POST['local_session_id'])) : '');
            ASSI_Notification::createChatNotification($requestId, sanitize_text_field(wp_unslash($_POST['session_id'])), $localSessionId);
            echo wp_json_encode(array('result' => false, 'error' => 'client_timeout', 'error_message' => ASSI_Tools::getErrorTranslation('client_timeout')));
            wp_die();
        }
        if (!isset($result->status) || $result->status != 'success' || !isset($result->chat_content->ai_output->content) || empty($result->chat_content->ai_output->content)) {
            if (isset($result->status) && $result->status == 'error') {
                echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result->message)), 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
                wp_die();
            }
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $mkd = new Parsedown();
        $answer = $mkd->text(sanitize_textarea_field(wp_unslash($result->chat_content->ai_output->content)));
        if (isset($result->user_data)) {
            $this->updatePlanDetails($result->user_data);
        }
        echo wp_json_encode(array('result' => true, 'chat_content' => $result->chat_content, 'answer' => $answer, 'answer_date' => sanitize_text_field(wp_unslash($result->chat_content->date)), 'session_id' => sanitize_text_field(wp_unslash($result->session_id)), 'chat_name' => sanitize_text_field(wp_unslash($result->chat_name)), 'user_data' => $this->convertUserData($result->user_data), 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
        wp_die();
    }

    public function chatDelete() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['session_id']) || empty($_POST['session_id'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'session_id' => sanitize_text_field(wp_unslash($_POST['session_id']))
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'chat/session/delete', $data, 30);
        if (isset($result->status) && $result->status == 'success') {
            echo wp_json_encode(array('result' => true));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            $error = sanitize_text_field(wp_unslash($result->message));
            echo wp_json_encode(array('result' => false, 'error' => $error, ASSI_Tools::getErrorTranslation($error)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function chatSaveMsgAsDraft() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['message']) || empty($_POST['message'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $mkd = new Parsedown();
        $text = $mkd->text(sanitize_textarea_field(wp_unslash($_POST['message'])));
        $text = preg_replace_callback(
            '/<li>(.*?)<\/li>/is',
            function ($matches) {
                $content = $matches[1];
                $content = preg_replace('#<p[^>]*>(.*?)</p>#is', '$1', $content);
                return '<li>' . $content . '</li>';
            },
            $text
        );
        $text = nl2br($text);
        $text = preg_replace_callback(
            '/<ul>(.*?)<\/ul>/is',
            function ($matches) {
                $content = $matches[1];
                $content = preg_replace('#<br\s*/?>#i', '', $content);
                return '<ul>' . $content . '</ul>';
            },
            $text
        );
        $text = preg_replace_callback(
            '/<ol>(.*?)<\/ol>/is',
            function ($matches) {
                $content = $matches[1];
                $content = preg_replace('#<br\s*/?>#i', '', $content);
                return '<ol>' . $content . '</ol>';
            },
            $text
        );
        $text = preg_replace_callback(
            '/<li>(.*?)<\/li>/is',
            function ($matches) {
                $content = $matches[1];
                $content = preg_replace('#<br\s*/?>#i', '', $content);
                return '<!-- wp:list-item --><li>' . $content . '</li><!-- /wp:list-item -->';
            },
            $text
        );

        $text = $this->convert_html_to_gutenberg_blocks($text);
        $text = preg_replace('/<hr\s*\/?>/i', '<!-- wp:separator --><hr class="wp-block-separator"/><!-- /wp:separator -->', $text);
        $text = preg_replace('/<br\s*\/?>/i', '', $text);
        $post = array(
            'post_title' => (isset($_POST['title']) && !empty($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : ''),
            'post_content' => $text,
            'post_status' => 'draft',
            'post_author' => get_current_user_id(),
            'post_type' => 'post'
        );
        if (isset($_POST['keywords']) && !empty($_POST['keywords'])) {
            $post['tax_input'] = array(
                'post_tag' => explode(', ', sanitize_text_field(wp_unslash($_POST['keywords'])))
            );
        }
        $postId = wp_insert_post($post, true);
        if ((int) $postId < 1) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $this->updatePostMetaData($postId, (isset($_POST['meta_description']) ? sanitize_text_field(wp_unslash($_POST['meta_description'])) : ''), (isset($_POST['focus_keyword']) ? sanitize_text_field(wp_unslash($_POST['focus_keyword'])) : ''));
        $editLink = get_edit_post_link($postId, false);
        if ((int) $postId > 0 && !empty($editLink)) {
            echo wp_json_encode(array('result' => true, 'edit' => $editLink));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    function convert_html_to_gutenberg_blocks($html) {
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
        libxml_clear_errors();
        $body = $dom->getElementsByTagName('body')->item(0);
        $output = '';
        foreach ($body->childNodes as $node) {
            if ($node->nodeType !== XML_ELEMENT_NODE) {
                continue;
            }
            $tag = strtolower($node->nodeName);
            $innerHTML = $dom->saveHTML($node);
            switch ($tag) {
                case 'p':
                    $output .= "<!-- wp:paragraph -->\n$innerHTML\n<!-- /wp:paragraph -->\n\n";
                    break;
                case 'h1':
                    $output .= "<!-- wp:heading {\"level\":1} -->\n$innerHTML\n<!-- /wp:heading -->\n\n";
                    break;
                case 'h2':
                    $output .= "<!-- wp:heading {\"level\":2} -->\n$innerHTML\n<!-- /wp:heading -->\n\n";
                    break;
                case 'h3':
                    $output .= "<!-- wp:heading {\"level\":3} -->\n$innerHTML\n<!-- /wp:heading -->\n\n";
                    break;
                case 'h4':
                    $output .= "<!-- wp:heading {\"level\":4} -->\n$innerHTML\n<!-- /wp:heading -->\n\n";
                    break;
                case 'ul':
                    $output .= "<!-- wp:list -->\n$innerHTML\n<!-- /wp:list -->\n\n";
                    break;
                case 'ol':
                    $output .= "<!-- wp:list {\"ordered\":true} -->\n$innerHTML\n<!-- /wp:list -->\n\n";
                    break;
                default:
                    $output .= $innerHTML . "\n\n";
                    break;
            }
        }
        return trim($output);
    }

    private function updatePostMetaData($postId, $metaDescription = '', $focusKeyword = '') {
        if (!empty($metaDescription)) {
            if (is_plugin_active('wordpress-seo/wp-seo.php')) {
                update_post_meta($postId, '_yoast_wpseo_metadesc', $metaDescription);
            } elseif (is_plugin_active('all-in-one-seo-pack/all_in_one_seo_pack.php')) {
                update_post_meta($postId, '_aioseop_description', $metaDescription);
            } elseif (is_plugin_active('seo-by-rank-math/rank-math.php')) {
                update_post_meta($postId, 'rank_math_description', $metaDescription);
            }
        }
        if (!empty($focusKeyword)) {
            if (is_plugin_active('wordpress-seo/wp-seo.php')) {
                update_post_meta($postId, '_yoast_wpseo_focuskw', $focusKeyword);
            } elseif (is_plugin_active('all-in-one-seo-pack/all_in_one_seo_pack.php')) {
                update_post_meta($postId, '_aioseop_keywords', $focusKeyword);
            } elseif (is_plugin_active('seo-by-rank-math/rank-math.php')) {
                update_post_meta($postId, 'rank_math_focus_keyword', $focusKeyword);
            }
        }
    }

    public function getDashboardActivity() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'sort_field' => 1
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'chat/session/get/list', $data);
        if (isset($result->status) && $result->status == 'success' && is_array($result->chat_sessions) && !empty($result->chat_sessions)) {
            $html = '';
            $wpDateFormat = get_option('date_format');
            $wpTimeFormat = get_option('time_format');
            $count = 0;
            foreach ($result->chat_sessions as $chat) {
                if ($count >= 3) {
                    break;
                }
                $html .= '<div class="card ass-dashboard-activity-card m-0" data-session-id="' . esc_attr($chat->session_id) . '">';
                $html .= '<div class="card-body my-3">';
                $html .= '<p class="text-truncate text-start mb-0 fw-bolder">' . (isset($chat->chat_name) && !empty($chat->chat_name) ? esc_html($chat->chat_name) : esc_html__('Chat', 'assistini')) . '</p>';
                $html .= '<p class="text-start text-muted small mb-0">' . esc_html(wp_date($wpDateFormat . ' ' . $wpTimeFormat, strtotime($chat->last_mod_date))) . '</p>';
                $html .= '</div>';
                $html .= '</div>';
                $count++;
            }
            echo wp_json_encode(array('result' => true, 'chat_sessions' => $html));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            $error = sanitize_text_field(wp_unslash($result->message));
            echo wp_json_encode(array('result' => false, 'error' => $error, 'error_message' => ASSI_Tools::getErrorTranslation($error)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function submitSupportTicket() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['name']) || empty($_POST['name']) || !isset($_POST['email']) || empty($_POST['email']) || !isset($_POST['message']) || empty($_POST['message'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'name' => sanitize_text_field(wp_unslash($_POST['name'])),
            'email' => sanitize_text_field(wp_unslash($_POST['email'])),
            'message' => sanitize_textarea_field(wp_unslash($_POST['message'])),
            'session_id' => (isset($_POST['session_id']) && !empty($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : ''),
            'chat_settings' => array(
                'template_id' => (isset($_POST['template_id']) && (int) $_POST['template_id'] > 0 ? (int) $_POST['template_id'] : 0),
                'language' => (isset($_POST['language']) && !empty($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : ''),
                'tone' => (isset($_POST['tone']) && !empty($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : ''),
                'point_of_view' => (isset($_POST['point_of_view']) && !empty($_POST['point_of_view']) ? sanitize_text_field(wp_unslash($_POST['point_of_view'])) : ''),
                'content_length' => (isset($_POST['content_length']) && !empty($_POST['content_length']) ? sanitize_text_field(wp_unslash($_POST['content_length'])) : '')
            )
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'support/create', $data);
        if (isset($result->status) && $result->status == 'success') {
            echo wp_json_encode(array('result' => true));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            $error = sanitize_text_field(wp_unslash($result->message));
            echo wp_json_encode(array('result' => false, 'error' => $error, 'error_message' => ASSI_Tools::getErrorTranslation($error)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function chatStartExpertMode() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $templateId = 1;
        if (isset($_POST['template_id']) && (int) $_POST['template_id'] > 0) {
            $templateId = (int) $_POST['template_id'];
        }
        $translations = ASSI_Tools::getSystemTemplateTranslation($templateId);
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'mode' => 2,
            'template_id' => $templateId,
            'template_name' => (isset($translations['header']) ? sanitize_text_field(wp_unslash($translations['header'])) : ''),
            'prompt_language' => (isset($_POST['language']) && !empty($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'en_US'),
            'request_id' => sanitize_text_field(wp_unslash(ASSI_Tools::createRequestId()))
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'chat/create', $data, 60);
        if (isset($result->status) && $result->status == 'success' && isset($result->session_id) && !empty($result->session_id) && isset($result->chat_content) && !empty($result->chat_content)) {
            echo wp_json_encode(array('result' => true, 'session_id' => sanitize_text_field(wp_unslash($result->session_id)), 'chat_content' => $result->chat_content));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            $error = sanitize_text_field(wp_unslash($result->message));
            echo wp_json_encode(array('result' => false, 'error' => $error, 'error_message' => ASSI_Tools::getErrorTranslation($error)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function checkOpenNotifications() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $type = 'chat';
        if (isset($_POST['type']) && !empty($_POST['type'])) {
            $type = sanitize_text_field(wp_unslash($_POST['type']));
        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $dbResult = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_notifications` WHERE `blog_user_id` = %d AND `type` = %s AND `status` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0), $type, 0));
        if (is_array($dbResult) && count($dbResult) > 0) {
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function notificationDelete() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['notification_id']) || ((int) $_POST['notification_id'] <= 0 && $_POST['notification_id'] != 'all')) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'notification_id' => ($_POST['notification_id'] == 'all' ? 'all' : (int) $_POST['notification_id'])
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'notification/delete', $data);
        if (isset($result->status) && $result->status == 'success') {
            global $wpdb;
            if ($_POST['notification_id'] == 'all') {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->query($wpdb->prepare(
                                "DELETE FROM `{$wpdb->prefix}assi_user_notifications` WHERE `blog_user_id` = %d",
                                (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)
                ));
            } else {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->query($wpdb->prepare(
                                "DELETE FROM `{$wpdb->prefix}assi_user_notifications` WHERE `notification_id` = %d AND `blog_user_id` = %d",
                                (int) $_POST['notification_id'],
                                (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)
                ));
            }
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function settingsGet() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $settings = get_option('ASSI_PLUGIN_BLOG_USER_OPTION_' . (int) ASSI_ACCOUNT_ASSI_USER_ID);
        if (is_array($settings) && !empty($settings)) {
            echo wp_json_encode(array('result' => true, 'settings' => $settings));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function settingsSave() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $settings = get_option('ASSI_PLUGIN_BLOG_USER_OPTION_' . (int) ASSI_PLUGIN_BLOG_USER_ID);
        if (!isset($_POST['type']) || empty($_POST['type'])) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $type = sanitize_text_field(wp_unslash($_POST['type']));
        if ($type == 'content_creator') {
            if (!isset($settings) || !is_array($settings)) {
                echo wp_json_encode(array('result' => false));
                wp_die();
            }
            if (isset($_POST['language']) && (!isset($settings['content_creator']['language']) || $settings['content_creator']['language'] != sanitize_text_field(wp_unslash($_POST['language'])))) {
                $settings['content_creator']['language'] = sanitize_text_field(wp_unslash($_POST['language']));
            }
            if (isset($_POST['tone']) && (!isset($settings['content_creator']['tone']) || $settings['content_creator']['tone'] != sanitize_text_field(wp_unslash($_POST['tone'])))) {
                $settings['content_creator']['tone'] = sanitize_text_field(wp_unslash($_POST['tone']));
            }
            if (isset($_POST['point_of_view']) && (!isset($settings['content_creator']['point_of_view']) || $settings['content_creator']['point_of_view'] != sanitize_text_field(wp_unslash($_POST['point_of_view'])))) {
                $settings['content_creator']['point_of_view'] = sanitize_text_field(wp_unslash($_POST['point_of_view']));
            }
            if (isset($_POST['content_length']) && (!isset($settings['content_creator']['content_length']) || $settings['content_creator']['content_length'] != sanitize_text_field(wp_unslash($_POST['content_length'])))) {
                $settings['content_creator']['content_length'] = sanitize_text_field(wp_unslash($_POST['content_length']));
            }
            update_option('ASSI_PLUGIN_BLOG_USER_OPTION_' . (int) ASSI_PLUGIN_BLOG_USER_ID, $settings, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        } else if ($type == 'image_generator') {
            if (!isset($settings) || !is_array($settings)) {
                echo wp_json_encode(array('result' => false));
                wp_die();
            }
            if (isset($_POST['size']) && (!isset($settings['image_generator']['size']) || $settings['image_generator']['size'] != sanitize_text_field(wp_unslash($_POST['size'])))) {
                $settings['image_generator']['size'] = sanitize_text_field(wp_unslash($_POST['size']));
            }
            if (isset($_POST['quality']) && (!isset($settings['image_generator']['quality']) || $settings['image_generator']['quality'] != sanitize_text_field(wp_unslash($_POST['quality'])))) {
                $settings['image_generator']['quality'] = sanitize_text_field(wp_unslash($_POST['quality']));
            }
            if (isset($_POST['output_format']) && (!isset($settings['image_generator']['output_format']) || $settings['image_generator']['output_format'] != sanitize_text_field(wp_unslash($_POST['output_format'])))) {
                $settings['image_generator']['output_format'] = sanitize_text_field(wp_unslash($_POST['output_format']));
            }
            update_option('ASSI_PLUGIN_BLOG_USER_OPTION_' . (int) ASSI_PLUGIN_BLOG_USER_ID, $settings, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function updateCreditsLeft() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['credits_left']) || (int) $_POST['credits_left'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $accountData = get_option('ASSI_PLUGIN_ACCOUNT');
        if (isset($accountData['plan']['credits_open'])) {
            $accountData['plan']['credits_open'] = (int) $_POST['credits_left'];
            update_option('ASSI_PLUGIN_ACCOUNT', $accountData, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function updateCreditsTotal() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['credits_total']) || (int) $_POST['credits_total'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $accountData = get_option('ASSI_PLUGIN_ACCOUNT');
        if (isset($accountData['plan']['credits_total'])) {
            $accountData['plan']['credits_total'] = (int) $_POST['credits_total'];
            update_option('ASSI_PLUGIN_ACCOUNT', $accountData, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function updateMaxChats() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['max_chats']) || (int) $_POST['max_chats'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $accountData = get_option('ASSI_PLUGIN_ACCOUNT');
        if (isset($accountData['plan']['max_chats'])) {
            $accountData['plan']['max_chats'] = (int) $_POST['max_chats'];
            update_option('ASSI_PLUGIN_ACCOUNT', $accountData, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function updateMaxTemplates() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['max_templates']) || (int) $_POST['max_templates'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $accountData = get_option('ASSI_PLUGIN_ACCOUNT');
        if (isset($accountData['plan']['max_templates'])) {
            $accountData['plan']['max_templates'] = (int) $_POST['max_templates'];
            update_option('ASSI_PLUGIN_ACCOUNT', $accountData, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function updatePlanId() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['plan_id']) || (int) $_POST['plan_id'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $accountData = get_option('ASSI_PLUGIN_ACCOUNT');
        if (isset($accountData['plan']['plan_id'])) {
            $accountData['plan']['plan_id'] = (int) $_POST['plan_id'];
            update_option('ASSI_PLUGIN_ACCOUNT', $accountData, false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function modalOnboardingClose() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $options = get_option('ASSI_PLUGIN_BLOG_USER_OPTION_' . ASSI_PLUGIN_BLOG_USER_ID);
        if (!$options) {
            $options = array();
        }
        $options['alert']['banner']['welcome'] = true;
        update_option('ASSI_PLUGIN_BLOG_USER_OPTION_' . ASSI_PLUGIN_BLOG_USER_ID, $options, false);
        echo json_encode(array('result' => true));
        wp_die();
    }

    public function settingsConsentSave() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!current_user_can('manage_options')) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_permission', 'error_message' => ASSI_Tools::getErrorTranslation('missing_permission')));
            wp_die();
        }
        if (isset($_POST['consent'])) {
            update_option('ASSI_PLUGIN_CONNECTION_TO_SERVER', ($_POST['consent'] == 'true' ? 1 : 0), false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    private function convertUserData($userData) {
        $return = array(
            'plan_id' => (isset($userData->ass_plan_id) ? (int) $userData->ass_plan_id : 0),
            'credits_open' => (isset($userData->ass_words_open) ? (int) $userData->ass_words_open : 0),
            'credits_total' => (isset($userData->ass_words_total) ? (int) $userData->ass_words_total : 0),
            'max_chats' => (isset($userData->ass_plan_max_count_chats) ? (int) $userData->ass_plan_max_count_chats : 0),
            'max_templates' => (isset($userData->ass_plan_max_count_template) ? (int) $userData->ass_plan_max_count_template : 0),
            'promotion' => array(
                'credits_open' => (isset($userData->ass_addon_quota->promotion->open_quota) ? (int) $userData->ass_addon_quota->promotion->open_quota : 0),
                'credits_total' => (isset($userData->ass_addon_quota->promotion->max_quota) ? (int) $userData->ass_addon_quota->promotion->max_quota : 0)
            ),
            'registered' => (isset($userData->registered) && (int) $userData->registered == 1 ? true : false),
            'bonus_available' => (isset($userData->bonus_available) && (int) $userData->bonus_available == 1 ? true : false),
            'display_name' => (isset($userData->ass_user_email) && !empty($userData->ass_user_email) ? sanitize_text_field(wp_unslash($userData->ass_user_email)) : ''),
        );
        return $return;
    }

    private function updatePlanDetails($userData, $userRemovedAuth = false) {
        $accountPlan = get_option('ASSI_PLUGIN_ACCOUNT');
        if (isset($userData->ass_plan_id)) {
            $accountPlan['plan']['plan_id'] = (int) $userData->ass_plan_id;
        }
        if (isset($userData->ass_words_open)) {
            $accountPlan['plan']['credits_open'] = (int) $userData->ass_words_open;
        }
        if (isset($userData->ass_words_total)) {
            $accountPlan['plan']['credits_total'] = (int) $userData->ass_words_total;
        }
        if (isset($userData->ass_words_total)) {
            $accountPlan['plan']['max_chats'] = (int) $userData->ass_plan_max_count_chats;
        }
        if (isset($userData->ass_words_total)) {
            $accountPlan['plan']['max_templates'] = (int) $userData->ass_plan_max_count_template;
        }
        if (isset($userData->ass_addon_quota->normal->open_quota)) {
            $accountPlan['plan']['addons']['normal']['credits_open'] = (int) $userData->ass_addon_quota->normal->open_quota;
        }
        if (isset($userData->ass_addon_quota->normal->max_quota)) {
            $accountPlan['plan']['addons']['normal']['credits_total'] = (int) $userData->ass_addon_quota->normal->max_quota;
        }
        if (isset($userData->ass_addon_quota->promotion->open_quota)) {
            $accountPlan['plan']['addons']['promotion']['credits_open'] = (int) $userData->ass_addon_quota->promotion->open_quota;
        }
        if (isset($userData->ass_addon_quota->promotion->max_quota)) {
            $accountPlan['plan']['addons']['promotion']['credits_total'] = (int) $userData->ass_addon_quota->promotion->max_quota;
        }
        if (isset($userData->registered)) {
            if (!$userRemovedAuth && isset($accountPlan['plan']['registered']) && $accountPlan['plan']['registered'] == true && !(int) $userData->registered > 0) {
                $globalAlerts = get_option('ASSI_PLUGIN_GLOBAL_ALERTS');
                if (!is_array($globalAlerts)) {
                    $globalAlerts = array();
                }
                $globalAlerts['lost_connection'] = array('email' => (isset($accountPlan['plan']['display_name']) ? $accountPlan['plan']['display_name'] : ''));
                update_option('ASSI_PLUGIN_GLOBAL_ALERTS', $globalAlerts, false);
            }
            $accountPlan['plan']['registered'] = ((int) $userData->registered > 0 ? true : false);
        }
        if (isset($userData->bonus_available)) {
            $accountPlan['plan']['bonus_available'] = ((int) $userData->bonus_available > 0 ? true : false);
        }
        if (isset($userData->ass_user_email)) {
            $accountPlan['plan']['display_name'] = (!empty($userData->ass_user_email) ? sanitize_text_field(wp_unslash($userData->ass_user_email)) : '');
        }
        update_option('ASSI_PLUGIN_ACCOUNT', $accountPlan, false);
    }
    
    public function editorSendPrompt() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['template_id']) || (int) $_POST['template_id'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        if (isset($_POST['request_id']) && !empty($_POST['request_id'])) {
            $requestId = sanitize_text_field(wp_unslash($_POST['request_id']));
        } else {
            $requestId = ASSI_Tools::createRequestId();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'request_id' => $requestId,
            'template_id' => (isset($_POST['is_system']) && $_POST['is_system'] == 'true' ? (int) $_POST['template_id'] : 0),
            'content' => isset($_POST['content']) && !empty($_POST['content']) ? sanitize_textarea_field(wp_unslash($_POST['content'])) : '',
            'number_of_results' => isset($_POST['number_of_results']) && (int) $_POST['number_of_results'] > 0 && (int) $_POST['number_of_results'] <= 5 ? (int) $_POST['number_of_results'] : 1,
            'focus_keyword' => isset($_POST['focus_keyword']) && !empty($_POST['focus_keyword']) ? sanitize_text_field(wp_unslash($_POST['focus_keyword'])) : '',
            'additional_content' => isset($_POST['additional_content']) && !empty($_POST['additional_content']) ? sanitize_textarea_field(wp_unslash($_POST['additional_content'])) : '',
            'url' => isset($_POST['url']) && !empty($_POST['url']) ? sanitize_text_field(wp_unslash($_POST['url'])) : '',
            'point_of_view' => isset($_POST['point_of_view']) && !empty($_POST['point_of_view']) ? sanitize_text_field(wp_unslash($_POST['point_of_view'])) : '',
            'tone' => isset($_POST['tone']) && !empty($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : '',
            'prompt_language' => isset($_POST['prompt_language']) && !empty($_POST['prompt_language']) ? sanitize_text_field(wp_unslash($_POST['prompt_language'])) : '',
            'refer_post_content' => isset($_POST['refer_post_content']) && !empty($_POST['refer_post_content']) ? sanitize_textarea_field(wp_unslash($_POST['refer_post_content'])) : ''
        );
        if (isset($_POST['is_system']) && $_POST['is_system'] != 'true') {
            global $wpdb;
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $dbResult = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_templates` WHERE (`blog_user_id` = %d OR `blog_access` = 1) AND `id` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0), (int) $_POST['template_id']));
            } else {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $dbResult = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_templates` WHERE `blog_user_id` = %d AND `id` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0), (int) $_POST['template_id']));
            }
            if (!is_object($dbResult) || empty($dbResult)) {
                echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
                wp_die();
            }
            $dbResult->custom_prompt = json_decode($dbResult->custom_prompt);
            $data['user_prompt'] = isset($dbResult->custom_prompt->prompt) && !empty($dbResult->custom_prompt->prompt) ? sanitize_textarea_field(wp_unslash($dbResult->custom_prompt->prompt)) : '';
            $data['reference_text'] = isset($dbResult->custom_prompt->reference_text) && !empty($dbResult->custom_prompt->reference_text) ? sanitize_textarea_field(wp_unslash($dbResult->custom_prompt->reference_text)) : '';
        } 
        
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'editor/create', $data, 90);
        if ($result == 'client_timeout' || $result == 'client_blocked' || $result == 'server_auth_failed' || $result == 'server_blocked') {
            if ($result == 'client_timeout') {
                $data['type'] = 'editor';
                $data['category'] = 'text';
                if ($data['template_id'] > 0) {
                    $data['is_system'] = true;
                } else {
                    $data['is_system'] = false;
                    $data['template_id'] = (int) $_POST['template_id'];
                }
                ASSI_Notification::createEditorNotification($requestId, 'editor', 'text', array('request_data' => $data));
            }
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result)), 'error_message' => ASSI_Tools::getErrorTranslation($result)));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            $contentArray = array();
            foreach ($result->content as $content) {
                $contentArray[] = wp_kses(nl2br($content), array('br' => array()));
            }
            $this->updatePlanDetails($result->user_data);
            $historyData = array(
                'request_data' => $data,
                'result_data' => $contentArray
            );
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                ASSI_History::createEntry($requestId, ((int) $data['template_id'] > 0 ? true : false), ((int) $data['template_id'] > 0 ? (int) $data['template_id'] : (int) $_POST['template_id']), 'editor', 'text', gmdate('Y-m-d H:i:s'), $historyData);
            }
            echo wp_json_encode(array('result' => true, 'content' => $contentArray, 'user_data' => $this->convertUserData($result->user_data), 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result->message)), 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function editorSendPromptImage() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['template_id']) || (int) $_POST['template_id'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $allowedMime = array('image/jpeg', 'image/jpg', 'image/png', 'image/webp');
        if (isset($_POST['request_id']) && !empty($_POST['request_id'])) {
            $requestId = sanitize_text_field(wp_unslash($_POST['request_id']));
        } else {
            $requestId = ASSI_Tools::createRequestId();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'request_id' => $requestId,
            'template_id' => isset($_POST['template_id']) && (int) $_POST['template_id'] > 0 ? (int) $_POST['template_id'] : 0,
            'user_input' => isset($_POST['content']) && !empty($_POST['content']) ? sanitize_textarea_field(wp_unslash($_POST['content'])) : '',
            'number_of_results' => 1,
            'additional_content' => isset($_POST['additional_content']) && !empty($_POST['additional_content']) ? sanitize_textarea_field(wp_unslash($_POST['additional_content'])) : '',
            'size' => isset($_POST['image_size']) && !empty($_POST['image_size']) ? sanitize_text_field(wp_unslash($_POST['image_size'])) : 'auto',
            'quality' => isset($_POST['image_quality']) && !empty($_POST['image_quality']) ? sanitize_text_field(wp_unslash($_POST['image_quality'])) : 'auto',
            'output_format' => isset($_POST['image_format']) && !empty($_POST['image_format']) ? sanitize_text_field(wp_unslash($_POST['image_format'])) : 'png',
            'model' => isset($_POST['model']) && !empty($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '',
            'art_style' => isset($_POST['art_style']) && !empty($_POST['art_style']) ? sanitize_text_field(wp_unslash($_POST['art_style'])) : '',
            'custom_style' => isset($_POST['custom_style']) && !empty($_POST['custom_style']) ? sanitize_textarea_field(wp_unslash($_POST['custom_style'])) : ''
        );
        $url = ASSI_PLUGIN_API_WP_ENDPOINT . 'image/create';
        if ((isset($_POST['image_id']) && (int) $_POST['image_id'] > 0) || (isset($_POST['image_url']) && !empty($_POST['image_url']))) { // image edit
            $url = ASSI_PLUGIN_API_WP_ENDPOINT . 'image/edit';
            if (isset($_POST['image_id']) && (int) $_POST['image_id'] > 0) {
                $attachment = get_post((int) $_POST['image_id']);
                if (!isset($attachment->post_mime_type) || empty($attachment->post_mime_type)) {
                    echo json_encode(array('result' => false, 'error' => 'image_not_found', 'error_message' => ASSI_Tools::getErrorTranslation('image_not_found')));
                    wp_die();
                }
                if (!in_array($attachment->post_mime_type, $allowedMime)) {
                    echo json_encode(array('result' => false, 'error' => 'invalid_mime_type', 'error_message' => ASSI_Tools::getErrorTranslation('invalid_mime_type')));
                    wp_die();
                }
                $filePath = get_attached_file((int) $_POST['image_id']);
                if (!file_exists($filePath)) {
                    echo json_encode(array('result' => false, 'error' => 'image_not_found', 'error_message' => ASSI_Tools::getErrorTranslation('image_not_found')));
                    wp_die();
                }
                $fileSize = filesize($filePath);
                if ($fileSize > 3 * 1024 * 1024) { // > 3MB
                    echo json_encode(array('result' => false, 'error' => 'image_size_limit', 'error_message' => ASSI_Tools::getErrorTranslation('image_size_limit')));
                    wp_die();
                }
            } else {
                $imageUrl = esc_url_raw(wp_unslash($_POST['image_url']));
                $response = wp_remote_get($imageUrl, array(
                    'timeout' => 30
                ));
                if (is_wp_error($response)) {
                    echo json_encode(array(
                        'result' => false,
                        'error' => 'image_not_found',
                        'error_message' => ASSI_Tools::getErrorTranslation('image_not_found')
                    ));
                    wp_die();
                }
                $body = wp_remote_retrieve_body($response);
                if (empty($body)) {
                    echo json_encode(array(
                        'result' => false,
                        'error' => 'image_not_found',
                        'error_message' => ASSI_Tools::getErrorTranslation('image_not_found')
                    ));
                    wp_die();
                }
                $tmpFile = wp_tempnam($imageUrl);
                if (!$tmpFile) {
                    echo json_encode(array(
                        'result' => false,
                        'error' => 'file_error',
                        'error_message' => 'Temporary file could not be created.'
                    ));
                    wp_die();
                }
                file_put_contents($tmpFile, $body);
                $mime = wp_check_filetype($imageUrl)['type'];
                if (empty($mime)) {
                    $mime = mime_content_type($tmpFile);
                }
                if (!in_array($mime, $allowedMime)) {
                    echo json_encode(array(
                        'result' => false,
                        'error' => 'invalid_mime_type',
                        'error_message' => ASSI_Tools::getErrorTranslation('invalid_mime_type')
                    ));
                    wp_die();
                }
                if (filesize($tmpFile) > 3 * 1024 * 1024) { // > 3 MB
                    echo json_encode(array(
                        'result' => false,
                        'error' => 'image_size_limit',
                        'error_message' => ASSI_Tools::getErrorTranslation('image_size_limit')
                    ));
                    wp_die();
                }
                $filePath = $tmpFile;
                $attachment = (object) ['post_mime_type' => $mime];
            }
            $result = ASSI_Request::postImage($url, $data, $filePath, basename($filePath), $attachment->post_mime_type, 300);
        } else {
            $result = ASSI_Request::post($url, $data, 300);
        }
        if ($result == 'client_timeout' || $result == 'client_blocked' || $result == 'server_auth_failed' || $result == 'server_blocked') {
            if ($result == 'client_timeout') {
                $data['type'] = 'editor';
                $data['category'] = 'image';
                ASSI_Notification::createEditorNotification($requestId, 'editor', 'image', array('request_data' => $data));
            }
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result)), 'error_message' => ASSI_Tools::getErrorTranslation($result)));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'error' && isset($result->message) && !empty($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result->message)), 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            $this->updatePlanDetails($result->user_data);
            $historyData = array(
                'request_data' => $data,
                'result_data' => ASSI_Tools::sanitizeArrayOrObject($result->content) 
            );
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                ASSI_History::createEntry($requestId, ((int) $data['template_id'] > 0 ? true : false), ((int) $data['template_id'] > 0 ? (int) $data['template_id'] : (int) $_POST['template_id']), 'editor', 'image', gmdate('Y-m-d H:i:s'), $historyData);
            }
            echo wp_json_encode(array('result' => true, 'content' => ASSI_Tools::sanitizeArrayOrObject($result->content), 'user_data' => $this->convertUserData($result->user_data), 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function editorInlineSendPrompt() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['template_id']) || (int) $_POST['template_id'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'request_id' => ASSI_Tools::createRequestId(),
            'template_id' => (isset($_POST['template_id']) && (int) $_POST['template_id'] > 0 ? (int) $_POST['template_id'] : 1),
            'content' => (isset($_POST['content']) && !empty($_POST['content']) ? sanitize_textarea_field(wp_unslash($_POST['content'])) : ''),
            'refer_post_content' => (isset($_POST['refer_post_content']) && !empty($_POST['refer_post_content']) ? sanitize_textarea_field(wp_unslash($_POST['refer_post_content'])) : ''),
            'number_of_results' => 1,
            'prompt_language' => 'auto'
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'editor/create', $data, 90);
        if ($result == 'client_timeout' || $result == 'client_blocked' || $result == 'server_auth_failed' || $result == 'server_blocked') {
            echo wp_json_encode(array('result' => false, 'error' => $result, 'error_message' => ASSI_Tools::getErrorTranslation($result)));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'error' && isset($result->message) && !empty($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result->message)), 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            $contentArray = array();
            foreach ($result->content as $content) {
                $contentArray[] = sanitize_text_field(wp_unslash($content));
            }
            $this->updatePlanDetails($result->user_data);
            echo wp_json_encode(array('result' => true, 'content' => $contentArray, 'user_data' => $this->convertUserData($result->user_data), 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function getPostFocusKeyword() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['post_id']) || (int) $_POST['post_id'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $focusKeyword = '';
        if (is_plugin_active('wordpress-seo/wp-seo.php')) {
            $focusKeyword = get_post_meta((int) $_POST['post_id'], '_yoast_wpseo_focuskw');
        } elseif (is_plugin_active('all-in-one-seo-pack/all_in_one_seo_pack.php')) {
            $focusKeyword = get_post_meta((int) $_POST['post_id'], '_aioseop_keywords');
        } elseif (is_plugin_active('seo-by-rank-math/rank-math.php')) {
            $focusKeyword = get_post_meta((int) $_POST['post_id'], 'rank_math_focus_keyword');
        }
        echo wp_json_encode(array('result' => true, 'focus_keyword' => $focusKeyword));
        wp_die();
    }

    public function checkOpenAiStatus() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $status = 0;
        $result = ASSI_Request::get(ASSI_PLUGIN_OPEN_AI_STATUS_ENDPOINT, 20);
        if (is_object($result) && !empty($result)) {
            foreach ($result as $key => $value) {
                if ($key == 'components') {
                    foreach ($value as $componentValue) {
                        if (isset($componentValue->name) && $componentValue->name == 'Chat Completions') {
                            if (isset($componentValue->status)) {
                                switch ($componentValue->status) {
                                    case 'operational':
                                        $status = 1;
                                        break;
                                    case 'degraded_performance':
                                    case 'partial_outage':
                                    case 'under_maintenance':
                                        $status = 2;
                                        break;
                                    case 'major_outage':
                                        $status = 3;
                                        break;
                                    default:
                                        $status = 0;
                                        break;
                                }
                            }
                        }
                    }
                }
            }
        }
        echo wp_json_encode(array('result' => true, 'status' => $status));
        wp_die();
    }

    public function chatChangeName() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['session_id']) || empty($_POST['session_id'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        if (!isset($_POST['chat_name']) || empty($_POST['chat_name'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'session_id' => sanitize_text_field(wp_unslash($_POST['session_id'])),
            'chat_name' => sanitize_text_field(wp_unslash($_POST['chat_name']))
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'chat/edit/name', $data, 30);
        if (isset($result->status) && $result->status == 'success') {
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function getBlogPosts() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $posts = get_posts();
        if (isset($posts) && !empty($posts)) {
            echo wp_json_encode(array('result' => true, 'posts' => $posts));
            wp_die();
        }
        echo wp_json_encode(array('result' => true, 'posts' => array()));
        wp_die();
    }
    public function uploadImageToLibrary() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!current_user_can('upload_files')) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_permission', 'error_message' => ASSI_Tools::getErrorTranslation('missing_permission')));
            wp_die();
        }
        if (!isset($_POST['image']) || empty($_POST['image'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $requestId = '';
        if (isset($_POST['request_id']) && !empty($_POST['request_id'])) {
            $requestId = sanitize_text_field(wp_unslash($_POST['request_id']));
        }
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $image_url = esc_url_raw(wp_unslash($_POST['image']));
        $response = wp_remote_get($image_url, array('timeout' => 30));
        if (is_wp_error($response)) {
            echo wp_json_encode(array('result' => false, 'error' => 'download_error', 'error_message' => 'Datei konnte nicht heruntergeladen werden.'));
            wp_die();
        }
        $image_data = wp_remote_retrieve_body($response);
        if (empty($image_data)) {
            echo wp_json_encode(array('result' => false, 'error' => 'empty_file', 'error_message' => 'Die heruntergeladene Datei ist leer.'));
            wp_die();
        }
        $uploadDir = wp_upload_dir();
        $filename = isset($_POST['filename']) && !empty($_POST['filename'])
            ? sanitize_text_field(wp_unslash($_POST['filename']))
            : basename(wp_parse_url($image_url, PHP_URL_PATH));
        $uniqueName = wp_unique_filename($uploadDir['path'], $filename);
        $filePath = trailingslashit($uploadDir['path']) . $uniqueName;
        file_put_contents($filePath, $image_data);
        $filetype = wp_check_filetype($uniqueName, null);
        $attachment = array(
            'post_mime_type' => $filetype['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', $uniqueName),
            'post_content' => (isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : ''),
            'post_status' => 'inherit'
        );
        $attachId = wp_insert_attachment($attachment, $filePath);
        if (!is_wp_error($attachId)) {
            $attachData = wp_generate_attachment_metadata($attachId, $filePath);
            wp_update_attachment_metadata($attachId, $attachData);
        }
        $attachUrl = wp_get_attachment_url($attachId);
        if ($attachUrl) {
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                ASSI_History::updateEntryUrl($requestId, $attachUrl, 'image');
            }
            ASSI_Notification::updateEntryUrl($requestId, $attachUrl, 'image');
        }
        echo wp_json_encode(array('result' => true, 'attachment_id' => $attachId, 'url' => $attachUrl));
        wp_die();
    }
    public function uploadAudioToLibrary() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!current_user_can('upload_files')) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_permission', 'error_message' => ASSI_Tools::getErrorTranslation('missing_permission')));
            wp_die();
        }
        if (!isset($_POST['audio']) || empty($_POST['audio'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $requestId = '';
        if (isset($_POST['request_id']) && !empty($_POST['request_id'])) {
            $requestId = sanitize_text_field(wp_unslash($_POST['request_id']));
        }
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $audio_url = esc_url_raw(wp_unslash($_POST['audio']));
        $response = wp_remote_get($audio_url, array('timeout' => 30));
        if (is_wp_error($response)) {
            echo wp_json_encode(array('result' => false, 'error' => 'download_error', 'error_message' => 'Datei konnte nicht heruntergeladen werden.'));
            wp_die();
        }
        $audio_data = wp_remote_retrieve_body($response);
        if (empty($audio_data)) {
            echo wp_json_encode(array('result' => false, 'error' => 'empty_file', 'error_message' => 'Die heruntergeladene Datei ist leer.'));
            wp_die();
        }
        $uploadDir = wp_upload_dir();
        $filename = isset($_POST['filename']) && !empty($_POST['filename'])
            ? sanitize_text_field(wp_unslash($_POST['filename']))
            : basename(wp_parse_url($audio_url, PHP_URL_PATH));
        $uniqueName = wp_unique_filename($uploadDir['path'], $filename);
        $filePath = trailingslashit($uploadDir['path']) . $uniqueName;
        file_put_contents($filePath, $audio_data);
        $filetype = wp_check_filetype($uniqueName, null);
        $attachment = array(
            'post_mime_type' => $filetype['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', $uniqueName),
            'post_content' => (isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : ''),
            'post_status' => 'inherit'
        );
        $attachId = wp_insert_attachment($attachment, $filePath);
        if (!is_wp_error($attachId)) {
            $attachData = wp_generate_attachment_metadata($attachId, $filePath);
            wp_update_attachment_metadata($attachId, $attachData);
        }
        $attachUrl = wp_get_attachment_url($attachId);
        if ($attachUrl) {
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                ASSI_History::updateEntryUrl($requestId, $attachUrl, 'audio');
            }
            ASSI_Notification::updateEntryUrl($requestId, $attachUrl, 'audio');
        }
        echo wp_json_encode(array('result' => true, 'attachment_id' => $attachId, 'url' => $attachUrl));
        wp_die();
    }

    public function settingsCustomAiVerify() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'engine' => 'openai'
        );
        if (isset($_POST['mode']) && (int) $_POST['mode'] == 1) {
            if (!isset($_POST['connection_id']) || (int) $_POST['connection_id'] <= 0) {
                echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
                wp_die();
            }
            $data['mode'] = 1;
            $data['connection_id'] = (int) $_POST['connection_id'];
        } else {
            if (!isset($_POST['key']) || empty($_POST['key'])) {
                echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
                wp_die();
            }
            $data['api_key'] = sanitize_text_field(wp_unslash($_POST['key']));
        }
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'custom/api/key/verify', $data, 30);
        if (isset($result->status) && $result->status == 'success') {
            echo wp_json_encode(array('result' => true, 'models' => (isset($result->models) ? $result->models : array()), 'default_options' => (isset($result->default_options) ? $result->default_options : array())));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function settingsCustomAiSave() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'name' => (isset($_POST['name']) && !empty($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : ''),
            'engine_options' => array(
                'text' => array(
                    'model' => (isset($_POST['text_model']) && !empty($_POST['text_model']) ? sanitize_text_field(wp_unslash($_POST['text_model'])) : ''),
                    'top_p' => (isset($_POST['text_top_p']) ? (float) $_POST['text_top_p'] : 0),
                    'temperature' => (isset($_POST['text_temperature']) ? (float) $_POST['text_temperature'] : 0),
                    'presence_penalty' => (isset($_POST['text_presence_penalty']) ? (float) $_POST['text_presence_penalty'] : 0),
                    'frequency_penalty' => (isset($_POST['text_frequency_penalty']) ? (float) $_POST['text_frequency_penalty'] : 0),
                ),
                'image' => array(
                    'model' => (isset($_POST['image_model']) && !empty($_POST['image_model']) ? sanitize_text_field(wp_unslash($_POST['image_model'])) : ''),
                )
            )
        );
        if (isset($_POST['mode']) && (int) $_POST['mode'] == 1) {
            if (!isset($_POST['connection_id']) || (int) $_POST['connection_id'] <= 0) {
                echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
                wp_die();
            }
            $data['mode'] = 1;
            $data['connection_id'] = (int) $_POST['connection_id'];
        } else {
            if (!isset($_POST['key']) || empty($_POST['key'])) {
                echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
                wp_die();
            }
            $data['api_key'] = sanitize_text_field(wp_unslash($_POST['key']));
        }
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'custom/api/key/add', $data, 30);
        if (isset($result->status) && $result->status == 'success' && isset($result->id) && (int) $result->id > 0) {
            $customData = array(
                'id' => (int) $result->id,
                'name' => (isset($result->name) ? $result->name : ''),
                'key' => (isset($result->key) ? $result->key : ''),
                'engine_options' => $data['engine_options'],
                'active' => 1
            );
            update_option('ASSI_PLUGIN_CUSTOM_AI_CONNECTION', $customData, false);
            echo wp_json_encode(array_merge(array('result' => true), $customData));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => $result->message, 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function settingsCustomAiRemove() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['connection_id']) || (int) $_POST['connection_id'] <= 0) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'id' => (int) $_POST['connection_id'],
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'custom/api/key/delete', $data, 30);
        if (isset($result->status) && $result->status == 'success') {
            update_option('ASSI_PLUGIN_CUSTOM_AI_CONNECTION', '', false);
            echo wp_json_encode(array('result' => true));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => $result->message, 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function settingsCustomAiChangeStatus() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['connection_id']) || (int) $_POST['connection_id'] <= 0) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        if (!isset($_POST['active']) || ((int) $_POST['active'] != 0 && (int) $_POST['active'] != 1)) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'id' => (int) $_POST['connection_id'],
            'active' => (int) $_POST['active'],
        );
        $option = get_option('ASSI_PLUGIN_CUSTOM_AI_CONNECTION');
        if (is_array($option)) {
            $option['active'] = (int) $_POST['active'];
            $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'custom/api/key/active', $data, 30);
            if (isset($result->status) && $result->status == 'success') {
                update_option('ASSI_PLUGIN_CUSTOM_AI_CONNECTION', $option, false);
                echo wp_json_encode(array('result' => true));
                wp_die();
            }
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function templateAssistantCreate() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $content = '';
        if (isset($_POST['post_id']) && (int) $_POST['post_id'] > 0) {
            $content = apply_filters('assi_the_content', get_post_field('post_content', (int) $_POST['post_id']));
        } else if (isset($_POST['content']) && !empty($_POST['content']) && is_string($_POST['content'])) {
            $content = sanitize_textarea_field(wp_unslash($_POST['content']));
        }
        if (empty($content)) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'content' => $content,
            'prompt_language' => 'auto'
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'custom/prompt/assistant', $data, 90);
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            echo wp_json_encode(array('result' => true, 'content' => $result->content));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => $result->message, 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function templateAssistantCreateStructure() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $content = '';
        if (isset($_POST['post_id']) && (int) $_POST['post_id'] > 0) {
            $content = apply_filters('assi_the_content', get_post_field('post_content', (int) $_POST['post_id']));
        } else if (isset($_POST['content']) && !empty($_POST['content']) && is_string($_POST['content'])) {
            $content = sanitize_textarea_field(wp_unslash($_POST['content']));
        }
        if (empty($content)) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'content' => $content,
            'prompt_language' => 'auto'
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'analyze/structure', $data, 90);
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            echo wp_json_encode(array('result' => true, 'content' => $result->content));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => $result->message, 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function templateAnalyzePrompt() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['prompt']) || empty($_POST['prompt'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_prompt', 'error_message' => ASSI_Tools::getErrorTranslation('missing_prompt')));
            wp_die();
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'prompt' => sanitize_textarea_field(wp_unslash($_POST['prompt'])),
            'prompt_language' => 'auto'
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'analyze/prompt', $data, 90);
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            echo wp_json_encode(array('result' => true, 'content' => $result->content));
            wp_die();
        } else if (isset($result->status) && $result->status == 'error' && isset($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result->message)), 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }

    public function saveCustomStyle() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['name']) || empty($_POST['name'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        if (!isset($_POST['content']) || empty($_POST['content'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $name = sanitize_text_field(wp_unslash($_POST['name']));
        $content = sanitize_textarea_field(wp_unslash($_POST['content']));
        $id = 0;
        if (isset($_POST['id']) && (int) $_POST['id'] > 0) {
            $id = (int) $_POST['id'];
        } else {
            $id = time();
        }
        $customStyles = get_option('ASSI_PLUGIN_CUSTOM_STYLES_' . ASSI_PLUGIN_BLOG_USER_ID);
        if (!is_array($customStyles) || !$customStyles) {
            $customStyles = array();
        }
        $customStyles[$id] = array('name' => $name, 'content' => $content, 'art' => (isset($_POST['art']) && !empty($_POST['art']) ? sanitize_text_field(wp_unslash($_POST['art'])) : ''));
        update_option('ASSI_PLUGIN_CUSTOM_STYLES_' . ASSI_PLUGIN_BLOG_USER_ID, $customStyles, false);
        echo wp_json_encode(array('result' => true, 'id' => $id, 'styles' => $customStyles));
        wp_die();
    }
    public function deleteCustomStyle() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['id']) || (int) $_POST['id'] <= 0) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $customStyles = get_option('ASSI_PLUGIN_CUSTOM_STYLES_' . ASSI_PLUGIN_BLOG_USER_ID);
        if (!is_array($customStyles) || !$customStyles) {
            echo wp_json_encode(array('result' => true, 'styles' => array()));
        }
        if (isset($customStyles[(int) $_POST['id']])) {
            unset($customStyles[(int) $_POST['id']]);
        }
        update_option('ASSI_PLUGIN_CUSTOM_STYLES_' . ASSI_PLUGIN_BLOG_USER_ID, $customStyles, false);
        echo wp_json_encode(array('result' => true, 'styles' => $customStyles));
        wp_die();
    }
    public function globalAlertDelete() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['type']) || empty($_POST['type'])) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        $type = sanitize_text_field(wp_unslash($_POST['type']));
        $globalAlerts = get_option('ASSI_PLUGIN_GLOBAL_ALERTS');
        if (is_array($globalAlerts) && isset($globalAlerts[$type])) {
            unset($globalAlerts[$type]);
            update_option('ASSI_PLUGIN_GLOBAL_ALERTS', $globalAlerts, false);
        }
        echo wp_json_encode(array('result' => true, 'global_alerts' => $globalAlerts));
        wp_die();
    }
    public function getEditorNotifications() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $dbResult = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_notifications` WHERE `blog_user_id` = %d AND `type` = %s AND `status` != %d ORDER BY `create_date` DESC", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0), 'editor', 0));
        if (is_array($dbResult) && count($dbResult) > 0) {
            foreach ($dbResult as $key => $value) {
                $dbResult[$key]->create_date = wp_date(get_option('date_format') . ' - ' . get_option('time_format'), strtotime($value->create_date));
            }
            echo wp_json_encode(array('result' => true, 'notifications' => ASSI_Tools::sanitizeArrayOrObject($dbResult)));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function deleteNotification() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }

        if (!isset($_POST['notification_id']) || (int) $_POST['notification_id'] <= 0) {
            echo wp_json_encode(array('result' => false, 'error' => 'missing_content', 'error_message' => ASSI_Tools::getErrorTranslation('missing_content')));
            wp_die();
        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM `{$wpdb->prefix}assi_user_notifications` WHERE `notification_id` = %d AND `blog_user_id` = %d",
                (int) $_POST['notification_id'],
                (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)
            )
        );
        if ($result) {
            echo wp_json_encode(array('result' => true));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function editorSendPromptAudio() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['template_id']) || (int) $_POST['template_id'] < 0) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        if (isset($_POST['request_id']) && !empty($_POST['request_id'])) {
            $requestId = sanitize_text_field(wp_unslash($_POST['request_id']));
        } else {
            $requestId = ASSI_Tools::createRequestId();
        }
        $isConversation = false;
        $content = '';
        if (isset($_POST['content']) && is_array($_POST['content'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            ASSI_Tools::sanitizeArrayOrObject($_POST['content'], true);
            $isConversation = true;
        } else if (isset($_POST['content']) && !empty($_POST['content'])) {
            $content = sanitize_textarea_field(wp_unslash($_POST['content']));
        }
        $additionalContent = '';
        if (!$isConversation) {
            if (isset($_POST['additional_content']) && !empty($_POST['additional_content'])) {
                $additionalContent = sanitize_textarea_field(wp_unslash($_POST['additional_content']));
            }
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'request_id' => $requestId,
            'template_id' => isset($_POST['template_id']) && (int) $_POST['template_id'] > 0 ? (int) $_POST['template_id'] : 0,
            'content' => $content,
            'additional_content' => $additionalContent,
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            'speakers' => isset($_POST['speakers']) && is_array($_POST['speakers']) ? ASSI_Tools::sanitizeArrayOrObject($_POST['speakers']) : '',
            'prompt_language' => isset($_POST['prompt_language']) && !empty($_POST['prompt_language']) ? sanitize_text_field(wp_unslash($_POST['prompt_language'])) : 'en_US',
            'output_format' => isset($_POST['output_format']) && !empty($_POST['output_format']) ? sanitize_text_field(wp_unslash($_POST['output_format'])) : 'mp3',
            'point_of_view' => isset($_POST['point_of_view']) && !empty($_POST['point_of_view']) ? sanitize_text_field(wp_unslash($_POST['point_of_view'])) : '',
            'tone' => isset($_POST['tone']) && !empty($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : ''
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'audio/podcast/create', $data, 300);
        if ($result == 'client_timeout' || $result == 'client_blocked' || $result == 'server_auth_failed' || $result == 'server_blocked') {
            if ($result == 'client_timeout') {
                $data['type'] = 'editor';
                $data['category'] = 'audio';
                ASSI_Notification::createEditorNotification($requestId, 'editor', 'audio', array('request_data' => $data));
            }
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result)), 'error_message' => ASSI_Tools::getErrorTranslation($result)));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'error' && isset($result->message) && !empty($result->message)) {
            echo wp_json_encode(array('result' => false, 'error' => sanitize_text_field(wp_unslash($result->message)), 'error_message' => ASSI_Tools::getErrorTranslation(sanitize_text_field(wp_unslash($result->message)))));
            wp_die();
        }
        if (isset($result->status) && $result->status == 'success' && isset($result->content) && !empty($result->content)) {
            $this->updatePlanDetails($result->user_data);
            $historyData = array(
                'request_data' => $data,
                'result_data' => ASSI_Tools::sanitizeArrayOrObject($result->content)
            );
            if (defined('ASSI_ACCOUNT_PLAN_ID') && (int) ASSI_ACCOUNT_PLAN_ID > 1) {
                ASSI_History::createEntry($requestId, ((int) $data['template_id'] > 0 ? true : false), ((int) $data['template_id'] > 0 ? (int) $data['template_id'] : (int) $_POST['template_id']), 'editor', 'audio', gmdate('Y-m-d H:i:s'), $historyData);
            }
            echo wp_json_encode(array('result' => true, 'content' => ASSI_Tools::sanitizeArrayOrObject($result->content), 'user_data' => $this->convertUserData($result->user_data), 'global_alerts' => get_option('ASSI_PLUGIN_GLOBAL_ALERTS')));
            wp_die();
        }
        echo wp_json_encode(array('result' => false));
        wp_die();
    }
    public function createNotification() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (!isset($_POST['request_data']) || empty($_POST['request_data'])) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        if (!isset($_POST['request_data']['request_id']) || empty($_POST['request_data']['request_id'])) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $requestId = sanitize_text_field(wp_unslash($_POST['request_data']['request_id']));
        $type = sanitize_text_field(wp_unslash(isset($_POST['type']) && !empty($_POST['type']) ? $_POST['type'] : ''));
        $category = sanitize_text_field(wp_unslash(isset($_POST['category']) && !empty($_POST['category']) ? $_POST['category'] : ''));
        if (isset($_POST['request_data']['action'])) {
            unset($_POST['request_data']['action']);
        }
        if (isset($_POST['request_data']['assi_security_nonce'])) {
            unset($_POST['request_data']['assi_security_nonce']);
        }
        if (isset($_POST['request_data']['request_id'])) {
            unset($_POST['request_data']['request_id']);
        }
        $_POST['request_data']['type'] = $type;
        $_POST['request_data']['category'] = $category;
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,	WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        ASSI_Notification::createEditorNotification($requestId, $type, $category, array('request_data' => ASSI_Tools::sanitizeArrayOrObject($_POST['request_data'], true)));
        echo wp_json_encode(array('result' => true));
        wp_die();
    }
    public function getEditorHistory() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        $blogUserId = (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0);
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $templateIds = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT template_id FROM `{$wpdb->prefix}assi_user_history` WHERE blog_user_id = %d", $blogUserId), 0);
        if (!is_array($templateIds) || count($templateIds) <= 0) {
            echo wp_json_encode(array('result' => true, 'history' => []));
            wp_die();
        }
        foreach ($templateIds as $templateId) {
            for ($sys = 0; $sys <= 1; $sys++) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->query($wpdb->prepare(
                    "DELETE FROM `{$wpdb->prefix}assi_user_history` WHERE `blog_user_id` = %d AND `template_id` = %d AND `is_system` = %d AND `request_id` NOT IN (SELECT request_id FROM (SELECT request_id FROM `{$wpdb->prefix}assi_user_history` WHERE `blog_user_id` = %d AND `template_id` = %d AND `is_system` = %d ORDER BY `create_date` DESC LIMIT 10) AS t)",
                    $blogUserId,
                    (int) $templateId,
                    (int) $sys,
                    $blogUserId,
                    (int) $templateId,
                    (int) $sys
                ));
            }
        }
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $dbResult = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_history` WHERE `blog_user_id` = %d ORDER BY `create_date` DESC", $blogUserId));
        if (is_array($dbResult) && count($dbResult) > 0) {
            foreach ($dbResult as $key => $value) {
                if (isset($value->create_date) && !empty($value->create_date)) {
                    $dbResult[$key]->timestamp = strtotime($value->create_date);
                    $dbResult[$key]->create_date = wp_date(get_option('date_format') . ' | ' . get_option('time_format'), strtotime($value->create_date));
                }
            }
            echo wp_json_encode(array('result' => true, 'history' => ASSI_Tools::sanitizeArrayOrObject($dbResult)));
            wp_die();
        }
        echo wp_json_encode(array('result' => true, 'history' => []));
        wp_die();
    }
    public function deleteHistory() {
        if (!current_user_can('read') || !check_ajax_referer('assi_security_nonce', 'assi_security_nonce', false)) {
            echo wp_json_encode(array('result' => false, 'error' => 'nonce', 'error_message' => ASSI_Tools::getErrorTranslation('nonce')));
            wp_die();
        }
        if (isset($_POST['request_id']) && !empty($_POST['request_id'])) {

        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM `{$wpdb->prefix}assi_user_history` WHERE `request_id` = %s AND `blog_user_id` = %d",
                sanitize_text_field(wp_unslash($_POST['request_id'])),
                (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)
            )
        );
        if (!$result) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        echo wp_json_encode(array('result' => true));
        wp_die();
    }
}
