<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp
if (!class_exists('AI_AutoTool_Prompt_Customer')) {
class AI_AutoTool_Prompt_Customer {
    public $options;
    private $options_label;
    public function __construct() {
        add_action('wp_ajax_save_content_prompt', array($this, 'save_content_callback'));
         add_action('admin_footer', array($this, 'add_javascript'));
        add_action('admin_init', array($this, 'page_init'));
        $this->options = get_option('aiautotool_prompt_options', array());
        if (empty($this->options)) {
            $this->initialize_options();
        }
        
           
        $this->options_label = array(
            'aiautotool_prompt_artcile' => 'Prompt create Article Full',
            'aiautotool_prompt_suggest_title' => 'Prompt Suggest Title ',
            'aiautotool_prompt_outline' => 'Prompt Create Outline',
            'aiautotool_prompt_intro' => 'Prompt Create Intro',
            'aiautotool_prompt_conclusion' => 'Prompt Create Conclusion',
            'aiautotool_prompt_faq' => 'Prompt Create FAQ',
            'aiautotool_prompt_seo_review' => 'Prompt Seo Review ',
            // 'aiautotool_prompt_rewrite_short' => 'Prompt rewrite Short ',
            // 'aiautotool_prompt_rewrite_long' => 'Prompt rewrite Long ',
            // 'aiautotool_prompt_rewrite_pro' => 'Prompt rewrite Pro '
        );
    }

    private function initialize_options() {
        $default_options = array(
            'aiautotool_prompt_artcile' => 'Assume you are a proficient writer skilled in persuasive copywriting. Write a text that is at least 1,500 words long. When preparing the article, use bold for necessary words. Pretend that you can write content so good that it can outrank other websites. Write a long, fully markdown formatted article. Assume your output will be published on a WordPress blog. Use natural language only. Please use perplexity and burstiness in your output.

Use full markdown formatting, including relevant H2 headings. Do not number the headings or subheadings. Do not include "subheading" in the subheadings.

Output in the following order:
Use this as the Title: [%%title%%]
Write an Executive Summary, using that as the title of an H2 heading.
Introduction: Include a 50 to 100 word introduction.
Create 3 FAQ.
Find the top 5 subtopics. Insert an H2 heading using the name of the subtopic before explaining each subtopic. Include a description of the subtopic. Then bullet point 4-6 important pieces for each subtopic with brief explanations about each.
Include a 100 to 150 word conclusion.
Include 5 relevant keyword tags based on the topic and subtopics you found.
Write all output in [%%lang%%]. ',
            'aiautotool_prompt_suggest_title' => 'Please give me an article title in language [%%lang%%] about %title%, Write all output in [%%lang%%]',
            'aiautotool_prompt_outline' => 'E-A-T stands for Expertise, Authoritativeness, and Trustworthiness. Create Engaging, Unique, and SEO Optimized Blog Post Outline from [%%title%%] keep in mind E-A-T. 
            You will be writing an outline for a given topic. First, think through how the article should be structured, given the searcher intent for the keyword. Provide these thoughts inside <analysis></analysis> tags. Then, provide the outline itself inside <outline></outline> tags. 
Write all output in [%%lang%%]',
            'aiautotool_prompt_intro' => 'My name is %author%. In the context of {%%cate%%}, create an introduction of up to 50 words, in %%lang%%, for my blog {%%blog%%}, for an article about: {%%title%%}. Place the HTML tag   in the most important sentences of the text.',
            'aiautotool_prompt_conclusion' => 'Write a conclusion to end an article about: {%%title%%} in the context of {%%cate%%}. Place the HTML tag <strong> </strong> in the most important sentences of the text.',
            'aiautotool_prompt_faq' => 'create 5 FAQ for article [%%title%%]',
            'aiautotool_prompt_seo_review' => '',
            
        );

        // Ensure $this->options is always an array
        if (!is_array($this->options)) {
            $this->options = array();
        }
       
        foreach ($default_options as $option_key => $option_value) {
            if (!isset($this->options[$option_key]) || empty($this->options[$option_key])) {
                $this->options[$option_key] = $option_value;
            }
        }

        update_option('aiautotool_prompt_options', $this->options);
    }
    

    public function render_setting() {
        // Create nonce for this page
        $prompt_nonce = wp_create_nonce('aiautotool_nonce');
        ?>
        <div class="wrap aiautotool-prompt-settings-wrap">
            <div class="aiautotool-prompt-header">
                <h2><i class="fa-solid fa-wand-magic-sparkles"></i> AI AutoTool Prompt Settings</h2>
                <p class="aiautotool-prompt-description">Customize your AI prompts for better content generation. Use tokens to dynamically insert content.</p>
            </div>
           <form method="post" action="options.php" id="aiautotool-prompt-form">
             
                <?php
                settings_fields('aiautotool_prompt_group');
                
                // Safely iterate through options
                if (is_array($this->options)) {
                    foreach ($this->options as $key => $value) {
                        $this->prompt_callback(array('option_name' => $key));
                    }
                }
                
                ?>
                <button type="submit" name="save" class="ft-submit">
                    <i class="fa-solid fa-floppy-disk"></i><?php esc_html_e('Save Prompt','ai-auto-tool'); ?>
                </button>
            </form>
            <script type="text/javascript">
                // Store nonce in a global variable for this page
                window.promptPageNonce = <?php echo json_encode($prompt_nonce); ?>;
            </script>
        </div>
        <?php
    }

    public function page_init() {
        register_setting(
            'aiautotool_prompt_group',
            'aiautotool_prompt_options',
            array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize')
            )
        );

        add_settings_section(
            'setting_section_id',
            'Edit Prompt Content',
            array($this, 'print_section_info'),
            'aiautotool-prompt-settings'
        );

        
    }

    public function print_section_info() {
        print 'Enter your desired prompt content below:';
    }

    public function prompt_callback($args) {
        $option_name = $args['option_name'];
        $option_value = '';
        
        // Safely get option value
        if (is_array($this->options) && isset($this->options[$option_name])) {
            $option_value = $this->options[$option_name];
        }

        // Thay thế các chuỗi dạng %xxx% thành thẻ span token
        $option_value = preg_replace('/%%([^%]+)%%/', '<span contenteditable="false" class="token">%%$1%%</span>', $option_value);
        
        ?>
        <div class="aiautotool-prompt-section">
            <p class="ft-note">
                <i class="fa-solid fa-lightbulb"></i>
                <?php echo esc_html(isset($this->options_label[$option_name]) ? $this->options_label[$option_name] : $option_name); ?>
            </p>
            
            <div class="aiautotool-token-buttons">
                <button class="aiautotool_btn_v1 aiautotool_btn_v12" onclick="insertSpan('%%title%%', event)">
                    <span class="dashicons dashicons-plus-alt2"></span>Title
                </button>
                <button class="aiautotool_btn_v1 aiautotool_btn_v12" onclick="insertSpan('%%cate%%', event)">
                    <span class="dashicons dashicons-plus-alt2"></span>Category
                </button>
                <!-- <button class="aiautotool_btn_v1 aiautotool_btn_v12" onclick="insertSpan('%%topic%%', event)">
                    <span class="dashicons dashicons-plus-alt2"></span>Topic
                </button> -->
                <button class="aiautotool_btn_v1 aiautotool_btn_v12" onclick="insertSpan('%%lang%%', event)">
                    <span class="dashicons dashicons-plus-alt2"></span>Language
                </button>
                <button class="aiautotool_btn_v1 aiautotool_btn_v12" onclick="insertSpan('%%content%%', event)">
                    <span class="dashicons dashicons-plus-alt2"></span>Content
                </button>
            </div>
            
            <div contenteditable="true" class="editable ft-code-textarea" data-option="<?php echo esc_attr($option_name); ?>">
                <?php echo wp_kses_post(stripslashes($option_value)); ?>
            </div>
        </div>

        <?php
    }

    public function sanitize($input) {
        $sanitized_input = array();
        foreach ($input as $key => $value) {
            $sanitized_input[$key] = strip_tags($value);
        }
        return $sanitized_input;
    }
    public function add_javascript() {
        ?>
         <style type="text/css">
            /* AI AutoTool Prompt Settings - Modern Design */
            .aiautotool-prompt-settings-wrap {
                background: #f8f9fa;
                padding: 20px;
                border-radius: 12px;
                margin: 20px 0;
            }

            .aiautotool-prompt-header {
                background: linear-gradient(135deg, var(--aiautotool-color, #00875c) 0%, #00b57b 100%);
                padding: 30px;
                border-radius: 12px 12px 0 0;
                margin: -20px -20px 24px -20px;
                box-shadow: 0 4px 12px rgba(0, 135, 92, 0.15);
            }

            .aiautotool-prompt-header h2 {
                color: #ffffff;
                margin: 0 0 8px 0;
                font-size: 28px;
                font-weight: 700;
                display: flex;
                align-items: center;
                gap: 12px;
            }

            .aiautotool-prompt-header h2 i {
                font-size: 30px;
            }

            .aiautotool-prompt-description {
                color: rgba(255, 255, 255, 0.9);
                margin: 0;
                font-size: 15px;
                line-height: 1.6;
            }

            #aiautotool-prompt-form {
                max-width: 100%;
                margin: 0 auto;
            }

            #aiautotool-prompt-form > p.ft-note {
                background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
                border-left: 4px solid var(--aiautotool-color, #00875c);
                padding: 16px 20px;
                margin: 20px 0;
                border-radius: 8px;
                font-size: 14px;
                line-height: 1.6;
                box-shadow: 0 2px 8px rgba(0, 135, 92, 0.08);
                animation: slideInFromTop 0.4s ease-out;
            }

            #aiautotool-prompt-form > p.ft-note i {
                color: var(--aiautotool-color, #00875c);
                margin-right: 8px;
                font-size: 16px;
            }

            /* Prompt Section Container */
            .aiautotool-prompt-section {
                background: #ffffff;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 24px;
                margin-bottom: 24px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 4px 12px rgba(0, 0, 0, 0.03);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                animation: fadeInUp 0.5s ease-out backwards;
            }

            .aiautotool-prompt-section:nth-child(1) { animation-delay: 0.05s; }
            .aiautotool-prompt-section:nth-child(2) { animation-delay: 0.1s; }
            .aiautotool-prompt-section:nth-child(3) { animation-delay: 0.15s; }
            .aiautotool-prompt-section:nth-child(4) { animation-delay: 0.2s; }
            .aiautotool-prompt-section:nth-child(5) { animation-delay: 0.25s; }
            .aiautotool-prompt-section:nth-child(6) { animation-delay: 0.3s; }
            .aiautotool-prompt-section:nth-child(7) { animation-delay: 0.35s; }

            .aiautotool-prompt-section:hover {
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07), 0 8px 20px rgba(0, 135, 92, 0.08);
                border-color: rgba(0, 135, 92, 0.3);
                transform: translateY(-2px);
            }

            /* Prompt Title/Label */
            .aiautotool-prompt-section .ft-note {
                background: linear-gradient(135deg, rgba(0, 135, 92, 0.08) 0%, rgba(0, 181, 123, 0.08) 100%);
                border-left: 4px solid var(--aiautotool-color, #00875c);
                padding: 12px 16px;
                margin: 0 0 16px 0;
                border-radius: 6px;
                font-size: 15px;
                font-weight: 600;
                color: #1f2937;
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .aiautotool-prompt-section .ft-note i {
                color: var(--aiautotool-color, #00875c);
                font-size: 18px;
                flex-shrink: 0;
            }

            /* Token Insert Buttons Container */
            .aiautotool-token-buttons {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                margin-bottom: 16px;
                padding: 12px;
                background: #f9fafb;
                border-radius: 8px;
                border: 1px dashed #d1d5db;
            }

            /* Token Insert Buttons */
            .aiautotool_btn_v1.aiautotool_btn_v12 {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                padding: 8px 14px;
                font-size: 13px;
                font-weight: 500;
                color: #374151;
                background: #ffffff;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                cursor: pointer;
                transition: all 0.2s ease;
                user-select: none;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            }

            .aiautotool_btn_v1.aiautotool_btn_v12:hover {
                background: var(--aiautotool-color, #00875c);
                color: #ffffff;
                border-color: var(--aiautotool-color, #00875c);
                transform: translateY(-1px);
                box-shadow: 0 4px 8px rgba(0, 135, 92, 0.2);
            }

            .aiautotool_btn_v1.aiautotool_btn_v12:active {
                transform: translateY(0);
                box-shadow: 0 1px 2px rgba(0, 135, 92, 0.2);
            }

            .aiautotool_btn_v1.aiautotool_btn_v12 .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
            }

            /* Editable Textarea */
            .editable.ft-code-textarea {
                border: 2px solid #e5e7eb;
                padding: 16px;
                margin-bottom: 0;
                min-height: 160px;
                max-height: 300px;
                font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
                font-size: 13px;
                line-height: 1.7;
                border-radius: 8px;
                background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
                resize: vertical;
                overflow-y: auto;
                box-sizing: border-box;
                white-space: pre-wrap;
                word-wrap: break-word;
                color: #1f2937;
                transition: all 0.2s ease;
            }

            .editable.ft-code-textarea:focus {
                outline: none;
                border-color: var(--aiautotool-color, #00875c);
                box-shadow: 0 0 0 3px rgba(0, 135, 92, 0.1);
                background: #ffffff;
            }

            .editable.ft-code-textarea::-webkit-scrollbar {
                width: 8px;
            }

            .editable.ft-code-textarea::-webkit-scrollbar-track {
                background: #f1f5f9;
                border-radius: 4px;
            }

            .editable.ft-code-textarea::-webkit-scrollbar-thumb {
                background: #cbd5e1;
                border-radius: 4px;
            }

            .editable.ft-code-textarea::-webkit-scrollbar-thumb:hover {
                background: var(--aiautotool-color, #00875c);
            }

            /* Token Spans */
            span.token {
                background: linear-gradient(135deg, var(--aiautotool-color, #00875c) 0%, #00b57b 100%);
                color: #ffffff;
                border-radius: 12px;
                padding: 3px 10px;
                margin: 0 3px;
                cursor: pointer;
                display: inline-block;
                font-size: 12px;
                font-weight: 600;
                line-height: 1.4;
                letter-spacing: 0.3px;
                transition: all 0.2s ease;
                box-shadow: 0 2px 4px rgba(0, 135, 92, 0.2);
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }

            span.token:hover {
                transform: scale(1.05);
                box-shadow: 0 4px 8px rgba(0, 135, 92, 0.3);
            }

            /* Submit Button */
            .ft-submit {
                margin-top: 24px;
                padding: 14px 32px;
                font-size: 15px;
                font-weight: 600;
                color: #ffffff;
                background: linear-gradient(135deg, var(--aiautotool-color, #00875c) 0%, #00b57b 100%);
                border: none;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                box-shadow: 0 4px 6px rgba(0, 135, 92, 0.2), 0 1px 3px rgba(0, 0, 0, 0.08);
                display: inline-flex;
                align-items: center;
                gap: 8px;
            }

            .ft-submit:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 16px rgba(0, 135, 92, 0.25), 0 2px 4px rgba(0, 0, 0, 0.1);
                background: linear-gradient(135deg, #007a52 0%, #00a06b 100%);
            }

            .ft-submit:active {
                transform: translateY(0);
                box-shadow: 0 2px 4px rgba(0, 135, 92, 0.2);
            }

            /* Animations */
            @keyframes fadeInUp {
                from {
                    opacity: 0;
                    transform: translateY(20px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            @keyframes slideInFromTop {
                from {
                    opacity: 0;
                    transform: translateY(-10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            /* Responsive Design */
            @media (max-width: 768px) {
                .aiautotool-prompt-settings-wrap {
                    padding: 12px;
                    margin: 10px 0;
                }

                .aiautotool-prompt-header {
                    padding: 20px;
                    margin: -12px -12px 16px -12px;
                }

                .aiautotool-prompt-header h2 {
                    font-size: 22px;
                    flex-direction: column;
                    align-items: flex-start;
                    gap: 8px;
                }

                .aiautotool-prompt-header h2 i {
                    font-size: 24px;
                }

                .aiautotool-prompt-description {
                    font-size: 14px;
                }

                .aiautotool-prompt-section {
                    padding: 16px;
                    margin-bottom: 16px;
                }

                .aiautotool-token-buttons {
                    gap: 6px;
                    padding: 10px;
                }

                .aiautotool_btn_v1.aiautotool_btn_v12 {
                    padding: 6px 10px;
                    font-size: 12px;
                }

                .editable.ft-code-textarea {
                    min-height: 120px;
                    font-size: 12px;
                    padding: 12px;
                }

                .ft-submit {
                    width: 100%;
                    justify-content: center;
                    padding: 12px 24px;
                }
            }

            /* Legacy prompt button style */
            .aiautotool_btn_prompt {
                padding: 5px 10px;
                font-size: 10px;
                user-select: none;
                display: inline-flex;
                text-transform: uppercase;
                align-items: center;
                border-color: var(--aiautotool-color);
                color: var(--colorDark);
                cursor: pointer;
                font-weight: 500;
                border-radius: 4px;
                transition: all 0.3s linear;
                font-family: inherit;
            }
        </style>
        <script>
            // Use nonce from window.promptPageNonce (set in render_setting) or create new one
            var promptPageNonce = (typeof window.promptPageNonce !== 'undefined') 
                ? window.promptPageNonce 
                : '<?php echo esc_js(wp_create_nonce('aiautotool_nonce')); ?>';
            
            console.log('Prompt page nonce:', promptPageNonce ? 'Yes (length: ' + promptPageNonce.length + ')' : 'No');
            
            // Ensure aiautotool_js_setting exists
            if (typeof aiautotool_js_setting === 'undefined') {
                aiautotool_js_setting = {};
            }
            
            // Always use the fresh nonce from this page
            aiautotool_js_setting.security = promptPageNonce;
            
            function saveContent() {
            	if (typeof showLoading === 'function') {
                    showLoading();
                }
                
                var data = {};
                jQuery('.editable').each(function() {
                    var optionName = jQuery(this).data('option');
                    if (optionName) {
                        var content = jQuery(this).html();
                        data[optionName] = content;
                    }
                });

                // Check if we have data
                if (Object.keys(data).length === 0) {
                    if (typeof hideLoading === 'function') {
                        hideLoading();
                    }
                    Swal.fire({
                        title: 'Error!',
                        text: 'No content to save.',
                        icon: 'error',
                        confirmButtonText: 'Đóng'
                    });
                    return;
                }

                // Use page-specific nonce
                var security = promptPageNonce || (typeof aiautotool_js_setting !== 'undefined' ? aiautotool_js_setting.security : '');
                    
                if (!security) {
                    console.error('Security nonce not found. Please refresh the page.');
                    if (typeof hideLoading === 'function') {
                        hideLoading();
                    }
                    Swal.fire({
                        title: 'Error!',
                        text: 'Security token not found. Please refresh the page and try again.',
                        icon: 'error',
                        confirmButtonText: 'Đóng'
                    });
                    return;
                }

                // Check if ajaxurl is defined
                var ajaxUrl = (typeof ajaxurl !== 'undefined') ? ajaxurl : '/wp-admin/admin-ajax.php';
                
                console.log('Saving prompt with data:', data);
                console.log('Security nonce:', security ? 'Present (length: ' + security.length + ')' : 'Missing');
                console.log('Nonce value (first 20 chars):', security ? security.substring(0, 20) : 'N/A');

                jQuery.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'save_content_prompt',
                        content: data,
                        security: security
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }
                        console.log('Save response:', response);
                        
                        if (response && response.success) {
                            Swal.fire({
                                title: 'Success!',
                                html: response.data && response.data.message ? response.data.message : 'Save Success!!!',
                                icon: 'success',
                                confirmButtonText: 'Đóng'
                            }).then((result) => {
                                 
                            });
                        } else {
                            var errorMsg = (response && response.data && response.data.message) 
                                ? response.data.message 
                                : 'Failed to save prompt. Please try again.';
                            Swal.fire({
                                title: 'Error!',
                                text: errorMsg,
                                icon: 'error',
                                confirmButtonText: 'Đóng'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }
                        console.error('AJAX Error:', status, error);
                        console.error('Status Code:', xhr.status);
                        console.error('Response Text:', xhr.responseText);
                        
                        var errorMsg = 'An error occurred while saving.';
                        if (xhr.status === 400) {
                            errorMsg = 'Bad Request (400). Please check if the security nonce is valid.';
                        } else if (xhr.status === 403) {
                            errorMsg = 'Permission denied. Please check your user permissions.';
                        } else if (xhr.status === 500) {
                            errorMsg = 'Server error. Please check the server logs.';
                        }
                        
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg + ' Check console for details.',
                            icon: 'error',
                            confirmButtonText: 'Đóng'
                        });
                    }
                });
            }

            function insertSpan(value, event) {
                event.preventDefault();
                var range = window.getSelection().getRangeAt(0);
                var newNode = document.createElement('span');
                newNode.className = 'token';
                newNode.textContent = value;
                newNode.contentEditable = false;
                range.collapse(false);
                range.insertNode(newNode);
            }

            jQuery(document).ready(function() {
                // Ensure ajaxurl is defined
                if (typeof ajaxurl === 'undefined') {
                    if (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.ajax_url) {
                        window.ajaxurl = aiautotool_js_setting.ajax_url;
                    } else {
                        window.ajaxurl = '/wp-admin/admin-ajax.php';
                    }
                }
                
                jQuery('#aiautotool-prompt-form').submit(function(event) {
                    event.preventDefault();
                    saveContent();
                });
            });

            var editableDivs = document.querySelectorAll('[contenteditable="true"]');
            editableDivs.forEach(function(div) {
            div.addEventListener('keydown', function(event) {
                // Kiểm tra nếu phím nhấn là Enter (mã 13)
                if (event.keyCode === 13) {
                    // Ngăn chặn hành động mặc định của phím Enter (xuống dòng)
                    event.preventDefault();

                    // Thêm kí tự \n vào vị trí hiện tại của văn bản
                    var selection = window.getSelection();
                    var range = selection.getRangeAt(0);
                    var newline = document.createTextNode('\n');
                    range.insertNode(newline);
                    range.setStartAfter(newline);
                    range.setEndAfter(newline);
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
            });
        });
        </script>
        <?php
    }

    public function save_content_callback() {
        // Check nonce first
        if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) {
            wp_send_json_error(array(
                'message' => __('Security check failed. Please refresh the page and try again.', 'ai-auto-tool')
            ));
            return;
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Permission denied. You do not have permission to perform this action.', 'ai-auto-tool')
            ));
            return;
        }
        
        // Validate and sanitize content
        if (!isset($_POST['content']) || !is_array($_POST['content'])) {
            wp_send_json_error(array(
                'message' => __('No content provided. Please fill in the prompt fields.', 'ai-auto-tool')
            ));
            return;
        }
        
        // Process and sanitize content
        $content = array();
        foreach ($_POST['content'] as $key => $item) {
            // Sanitize the key
            $sanitized_key = sanitize_key($key);
            
            // Sanitize the content - preserve HTML but sanitize it
            // Use wp_kses_post to allow safe HTML tags
            $processed_content = wp_kses_post($item);
            
            // Convert newlines to <br> tags
            $content[$sanitized_key] = nl2br($processed_content);
        }
        
        // Validate that we have content
        if (empty($content)) {
            wp_send_json_error(array(
                'message' => __('No valid content to save. Please check your input.', 'ai-auto-tool')
            ));
            return;
        }
        
        // Save the content
        $result = update_option('aiautotool_prompt_options', $content);
        
        if ($result !== false) {
            // Update local options for immediate use
            $this->options = $content;
            
            wp_send_json_success(array(
                'message' => __('Prompt saved successfully!', 'ai-auto-tool')
            ));
        } else {
            wp_send_json_error(array(
                'message' => __('Failed to save prompt. The data may be unchanged or there was a database error.', 'ai-auto-tool')
            ));
        }
    }
}
} // End of class_exists check
