<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

if (!class_exists('AIautotool_Prompt_CPT')) {
class AIautotool_Prompt_CPT extends rendersetting{
    public  $active = true;
    public  $active_option_name = 'AIautotool_Prompt_CPT_active'; // Match with integrations page
    public $aiautotool_config_settings;
    public  $usage_option_name = 'prompt_manager_usage';
   
    public  $icon = '<i class="fa-brands fa-cloudflare"></i>';
    private $client = null;
    public $notices = [];
    public $limit = AIAUTOTOOL_FREE;
    private $plan_limit_aiautotool ;
    public $name_plan ;
    public $config = array();
    public $notice ;
    public $aiautotool_setting_cloudflare_image;

     public function __construct() {
        // Defer translation until textdomain is loaded (WordPress 6.7.0+ requirement)
        // Translation will be done via getter method when actually needed
        $this->name_plan = null;
        $this->plan_limit_aiautotool =  'plan_limit_aiautotool_'.$this->active_option_name;
       
        
        $this->notice = new aiautotool_Warning_Notice();
        
        // Check both option names for backward compatibility
        $new_option = get_option($this->active_option_name, false);
        $old_option = get_option('Aiautotool_prompt_manager_active', false);
        
        // Use new option if set, otherwise check old option
        if ($new_option !== false) {
            $this->active = $new_option;
        } elseif ($old_option !== false) {
            // Migrate old option to new option name
            $this->active = $old_option;
            update_option($this->active_option_name, $old_option);
            // Keep old option for now to avoid breaking things
        } else {
            $this->active = false;
        }
        
        // Always add hooks, but check active status in callbacks
        // This ensures menu appears even if feature is activated after class instantiation
        add_action('init', [$this, 'maybe_register_prompt_cpt']);
        add_action('admin_init', [$this, 'maybe_create_default_prompts'], 10); // Check and create prompts on admin load
        add_action('admin_menu', [$this, 'maybe_add_prompt_to_menu'], 20); // Higher priority to ensure parent menu exists
        add_action('add_meta_boxes', [$this, 'maybe_add_metabox']);
        add_action('save_post', [$this, 'maybe_save_metabox']);
        add_action('wp_ajax_aiautotool_load_customer_prompt_properties', [$this, 'aiautotool_load_customer_prompt_properties']);
        
        add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_callback'));

        // Initialize if already active
        if ($this->active=='true') {
            // Flush rewrite rules to ensure CPT is registered
            add_action('admin_init', [$this, 'maybe_flush_rewrite_rules'], 999);
        }
    }

    /**
     * Get translated name_plan value
     * Translates on-demand to comply with WordPress 6.7.0+ requirement
     * that translations should be loaded at 'init' action or later
     */
    public function get_name_plan() {
        if ($this->name_plan === null) {
            // Ensure textdomain is loaded before translating
            if (!is_textdomain_loaded('ai-auto-tool') && did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
            $this->name_plan = __('Prompt Manager', 'ai-auto-tool');
        }
        return $this->name_plan;
    }

    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active, null, 'no');
            
            // Update local active status
            $this->active = $active;
            
            // Force re-register CPT if activating
            if ($active === 'true') {
                // Register CPT immediately (even though it will be registered on next init)
                // This ensures it's available right away
                if (!post_type_exists('aiautotool_prompts')) {
                    self::register_prompt_cpt();
                }
                
                // Create default prompts when activating
                $this->create_default_prompts();
            }
            
            // Flush rewrite rules when activated/deactivated
            flush_rewrite_rules(false);
            
            // Return active status (backward compatibility)
            print_r($active);
        }

        wp_die();
    }
    
    /**
     * Check if feature is active before registering CPT
     */
    public function maybe_register_prompt_cpt() {
        $this->active = get_option($this->active_option_name, false);
        if ($this->active === 'true') {
            self::register_prompt_cpt();
        }
    }
    
    /**
     * Check if feature is active and create default prompts if needed
     */
    public function maybe_create_default_prompts() {
        // Only run once per page load
        static $checked = false;
        if ($checked) {
            return;
        }
        $checked = true;
        
        $this->active = get_option($this->active_option_name, false);
        if ($this->active === 'true') {
            // Ensure CPT is registered first
            if (!post_type_exists('aiautotool_prompts')) {
                self::register_prompt_cpt();
            }
            // Create default prompts if they don't exist
            $this->create_default_prompts();
        }
    }
    
    /**
     * Create 5 default prompts for article creation
     */
    public function create_default_prompts() {
        // Debug log
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('AI Auto Tool: create_default_prompts() called');
        }
        
        // Ensure CPT is registered
        if (!post_type_exists('aiautotool_prompts')) {
            self::register_prompt_cpt();
        }
        
        // Check if default prompts already exist by counting existing prompts
        $existing_posts = get_posts(array(
            'post_type' => 'aiautotool_prompts',
            'post_status' => 'any',
            'posts_per_page' => -1,
            'fields' => 'ids'
        ));
        
        // If we already have 5 or more prompts, assume defaults were created
        // But also check the option flag for backward compatibility
        $default_prompts_created = get_option('aiautotool_default_prompts_created', false);
        if ($default_prompts_created && count($existing_posts) >= 5) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: Default prompts already exist, skipping creation');
            }
            return; // Already created
        }
        
        // Define 5 default prompts
        $default_prompts = array(
            array(
                'title' => __('SEO Article Prompt', 'ai-auto-tool'),
                'content' => __('Write a comprehensive SEO-optimized article about %%title%% in %%lang%% language. The article should be well-structured with an engaging introduction, detailed body paragraphs, and a strong conclusion. Include relevant keywords naturally throughout the content. Make sure the content is informative, valuable, and provides actionable insights for readers. Use clear headings and subheadings to improve readability. Length: approximately 1000-1500 words. Write the entire article in %%lang%% language.', 'ai-auto-tool'),
                'params' => array(
                    array(
                        'label' => '%%title%%',
                        'value' => '%%title%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%lang%%',
                        'value' => '%%lang%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%blog%%',
                        'value' => '%%blog%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%cate%%',
                        'value' => '%%cate%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%content%%',
                        'value' => '%%content%%',
                        'type' => 'input_text'
                    )
                )
            ),
            array(
                'title' => __('How-to Guide Prompt', 'ai-auto-tool'),
                'content' => __('Create a detailed step-by-step guide on how to %%title%% in %%lang%% language. The guide should be beginner-friendly with clear instructions, practical examples, and helpful tips. Include prerequisites if needed, and explain each step thoroughly. Add troubleshooting tips for common issues. Make the content easy to follow and actionable. Write the entire guide in %%lang%% language.', 'ai-auto-tool'),
                'params' => array(
                    array(
                        'label' => '%%title%%',
                        'value' => '%%title%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%lang%%',
                        'value' => '%%lang%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%blog%%',
                        'value' => '%%blog%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%cate%%',
                        'value' => '%%cate%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%content%%',
                        'value' => '%%content%%',
                        'type' => 'input_text'
                    )
                )
            ),
            array(
                'title' => __('Product Review Prompt', 'ai-auto-tool'),
                'content' => __('Write an honest and comprehensive review of %%title%% in %%lang%% language. Include an overview of the product, its key features, pros and cons, pricing information, and a final verdict. Compare it with similar products if relevant. Provide real-world usage examples and recommendations for who should consider this product. Be objective and balanced in your assessment. Write the entire review in %%lang%% language.', 'ai-auto-tool'),
                'params' => array(
                    array(
                        'label' => '%%title%%',
                        'value' => '%%title%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%lang%%',
                        'value' => '%%lang%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%blog%%',
                        'value' => '%%blog%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%cate%%',
                        'value' => '%%cate%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%content%%',
                        'value' => '%%content%%',
                        'type' => 'input_text'
                    )
                )
            ),
            array(
                'title' => __('News Article Prompt', 'ai-auto-tool'),
                'content' => __('Write a news article about %%title%% in %%lang%% language. Follow journalistic standards with a clear headline, lead paragraph that answers who, what, when, where, and why, followed by detailed information. Include relevant background context, quotes from sources if applicable, and implications of the news. Maintain objectivity and accuracy throughout the article. Write the entire article in %%lang%% language.', 'ai-auto-tool'),
                'params' => array(
                    array(
                        'label' => '%%title%%',
                        'value' => '%%title%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%lang%%',
                        'value' => '%%lang%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%blog%%',
                        'value' => '%%blog%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%cate%%',
                        'value' => '%%cate%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%content%%',
                        'value' => '%%content%%',
                        'type' => 'input_text'
                    )
                )
            ),
            array(
                'title' => __('Blog Post Prompt', 'ai-auto-tool'),
                'content' => __('Create an engaging blog post about %%title%% in %%lang%% language. Write in a conversational and friendly tone that connects with readers. Share personal insights, experiences, or opinions while providing valuable information. Use storytelling elements to make it interesting. Include a compelling introduction that hooks the reader and a conclusion that encourages engagement or action. Write the entire blog post in %%lang%% language.', 'ai-auto-tool'),
                'params' => array(
                    array(
                        'label' => '%%title%%',
                        'value' => '%%title%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%lang%%',
                        'value' => '%%lang%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%blog%%',
                        'value' => '%%blog%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%cate%%',
                        'value' => '%%cate%%',
                        'type' => 'input_text'
                    ),
                    array(
                        'label' => '%%content%%',
                        'value' => '%%content%%',
                        'type' => 'input_text'
                    )
                )
            )
        );
        
        // Get existing titles from the posts we already queried
        $existing_titles = array();
        foreach ($existing_posts as $post_id) {
            $existing_titles[] = get_the_title($post_id);
        }
        
        // Create each prompt
        $created_count = 0;
        $skipped_count = 0;
        foreach ($default_prompts as $prompt_data) {
            // Check if prompt with same title already exists
            if (!in_array($prompt_data['title'], $existing_titles, true)) {
                $post_id = wp_insert_post(array(
                    'post_title' => $prompt_data['title'],
                    'post_content' => $prompt_data['content'],
                    'post_status' => 'publish',
                    'post_type' => 'aiautotool_prompts',
                    'post_author' => get_current_user_id() ?: 1,
                ));
                
                if ($post_id && !is_wp_error($post_id)) {
                    // Save prompt parameters
                    if (!empty($prompt_data['params'])) {
                        update_post_meta($post_id, '_aiautotool_prompt_params', $prompt_data['params']);
                    }
                    $created_count++;
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        error_log('AI Auto Tool: Created prompt: ' . $prompt_data['title'] . ' (ID: ' . $post_id . ')');
                    }
                } else {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        $error_msg = is_wp_error($post_id) ? $post_id->get_error_message() : 'Unknown error';
                        error_log('AI Auto Tool: Failed to create prompt: ' . $prompt_data['title'] . ' - ' . $error_msg);
                    }
                }
            } else {
                $skipped_count++;
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('AI Auto Tool: Skipped prompt (already exists): ' . $prompt_data['title']);
                }
            }
        }
        
        // Mark default prompts as created if we created at least one
        if ($created_count > 0) {
            update_option('aiautotool_default_prompts_created', true);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: Created ' . $created_count . ' default prompts, skipped ' . $skipped_count);
            }
        } else if ($skipped_count > 0) {
            // All prompts already exist, mark as created
            update_option('aiautotool_default_prompts_created', true);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: All default prompts already exist (' . $skipped_count . ' skipped)');
            }
        }
    }
    
    /**
     * Check if feature is active before adding menu
     * Always add menu manually to ensure it appears
     */
    public function maybe_add_prompt_to_menu() {
        // Get fresh active status from database
        $active_status = get_option($this->active_option_name, false);
        
        // Debug log
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('AI Auto Tool: maybe_add_prompt_to_menu() called');
            error_log('AI Auto Tool: Active status = ' . var_export($active_status, true));
            error_log('AI Auto Tool: Active option name = ' . $this->active_option_name);
        }
        
        // Check if active (support both 'true' string and boolean true)
        if ($active_status === 'true' || $active_status === true) {
            // Always add menu manually to ensure it appears
            // Even though CPT registration should create it, we add it explicitly
            self::add_prompt_to_menu();
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: Menu add attempted');
            }
        } else {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: Feature not active, skipping menu');
            }
        }
    }
    
    /**
     * Check if feature is active before adding metabox
     */
    public function maybe_add_metabox() {
        $this->active = get_option($this->active_option_name, false);
        if ($this->active === 'true') {
            self::add_metabox();
        }
    }
    
    /**
     * Check if feature is active before saving metabox
     */
    public function maybe_save_metabox($post_id) {
        $this->active = get_option($this->active_option_name, false);
        if ($this->active === 'true') {
            self::save_metabox($post_id);
        }
    }
    
    /**
     * Flush rewrite rules once after activation
     */
    public function maybe_flush_rewrite_rules() {
        static $flushed = false;
        if (!$flushed) {
            flush_rewrite_rules(false);
            $flushed = true;
        }
    }
    
    /**
     * Legacy init method - kept for backward compatibility
     * @deprecated Use individual maybe_* methods instead
     */
    public function init(){
        // This method is now handled by constructor hooks
        // Kept for backward compatibility
    }


    public function aiautotool_load_customer_prompt_properties() {
        // Check if Prompt Manager feature is active
        $prompt_manager_active = get_option('AIautotool_Prompt_CPT_active', false);
        if ($prompt_manager_active !== 'true') {
            wp_send_json_error(array(
                'message' => __('Prompt Manager feature is not active. Please activate it in settings to use prompts.', 'ai-auto-tool')
            ));
            wp_die();
        }
        
        $arr_replace_prompt = ['%%title%%','%%lang%%','%%blog%%','%%cate%%','%%content%%'];
        $prompt_id = isset($_POST['prompt_id']) ? sanitize_text_field($_POST['prompt_id']) : '';
        
        if (empty($prompt_id)) {
            wp_send_json_error(array(
                'message' => __('Invalid prompt ID.', 'ai-auto-tool')
            ));
            wp_die();
        }
        
        $postprompt = get_post($prompt_id);
        if (!$postprompt || $postprompt->post_type !== 'aiautotool_prompts') {
            wp_send_json_error(array(
                'message' => __('Prompt not found.', 'ai-auto-tool')
            ));
            wp_die();
        }
        
        $params = get_post_meta($prompt_id, '_aiautotool_prompt_params', true);
        $arr = array();
        $arr['prompt_content'] = esc_html($postprompt->post_content);
        $arr['prompt_params'] = $params;
        $arr['prompt_arr_replace'] = esc_html($arr_replace_prompt);
        wp_send_json_success($arr);
        wp_die(); 
    }
    public function render_select_prompt(){
        $allprompt = get_option('aiautotool_prompt_options',array());
        $artcle_prompt = '';
        if(isset($allprompt['aiautotool_prompt_artcile']))
        {
            $artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
        }
        
        // Check if Prompt Manager feature is active
        $prompt_manager_active = get_option('AIautotool_Prompt_CPT_active', false);
        $is_prompt_active = ($prompt_manager_active === 'true');
        ?>
        
        <!-- Prompt Selection Mode -->
        <p class="ft-note"><i class="fa-solid fa-lightbulb"></i> <?php esc_html_e('Prompt Selection Mode:', 'ai-auto-tool'); ?></p>
        <div class="prompt-mode-selector" style="margin-bottom: 20px;">
            <div class="prompt-mode-option">
                <input type="radio" name="prompt_selection_mode" id="prompt_mode_single" value="single" checked>
                <label for="prompt_mode_single" class="prompt-mode-label">
                    <span class="prompt-mode-icon"><i class="fa-solid fa-file-lines"></i></span>
                    <span class="prompt-mode-content">
                        <span class="prompt-mode-title"><?php esc_html_e('Option 1: Single Prompt', 'ai-auto-tool'); ?></span>
                        <span class="prompt-mode-desc"><?php esc_html_e('Use a single prompt for all posts', 'ai-auto-tool'); ?></span>
                    </span>
                    <span class="prompt-mode-check"><i class="fa-solid fa-check-circle"></i></span>
                </label>
            </div>
            <div class="prompt-mode-option">
                <input type="radio" name="prompt_selection_mode" id="prompt_mode_multiple" value="multiple">
                <label for="prompt_mode_multiple" class="prompt-mode-label">
                    <span class="prompt-mode-icon"><i class="fa-solid fa-shuffle"></i></span>
                    <span class="prompt-mode-content">
                        <span class="prompt-mode-title"><?php esc_html_e('Option 2: Multiple Prompts', 'ai-auto-tool'); ?></span>
                        <span class="prompt-mode-desc"><?php esc_html_e('Select multiple prompts and randomly use one for each post title', 'ai-auto-tool'); ?></span>
                    </span>
                    <span class="prompt-mode-check"><i class="fa-solid fa-check-circle"></i></span>
                </label>
            </div>
            <div class="prompt-mode-option">
                <input type="radio" name="prompt_selection_mode" id="prompt_mode_auto" value="auto">
                <label for="prompt_mode_auto" class="prompt-mode-label">
                    <span class="prompt-mode-icon"><i class="fa-solid fa-magic"></i></span>
                    <span class="prompt-mode-content">
                        <span class="prompt-mode-title"><?php esc_html_e('Option 3: Auto Prompt', 'ai-auto-tool'); ?></span>
                        <span class="prompt-mode-desc"><?php esc_html_e('Use generate_article_from_title with auto prompt', 'ai-auto-tool'); ?></span>
                    </span>
                    <span class="prompt-mode-check"><i class="fa-solid fa-check-circle"></i></span>
                </label>
            </div>
        </div>
        
        <style>
        .prompt-mode-selector {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .prompt-mode-option {
            flex: 1;
            min-width: 280px;
        }
        
        .prompt-mode-option input[type="radio"] {
            display: none;
        }
        
        .prompt-mode-label {
            display: flex;
            align-items: center;
            padding: 18px 20px;
            background: #ffffff;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }
        
        .prompt-mode-label::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(135deg, #4a90e2, #357abd);
            transform: scaleY(0);
            transition: transform 0.3s ease;
        }
        
        .prompt-mode-label:hover {
            border-color: #4a90e2;
            box-shadow: 0 4px 12px rgba(74, 144, 226, 0.15);
            transform: translateY(-2px);
        }
        
        .prompt-mode-option input[type="radio"]:checked + .prompt-mode-label {
            border-color: #4a90e2;
            background: linear-gradient(135deg, rgba(74, 144, 226, 0.05), rgba(53, 122, 189, 0.05));
            box-shadow: 0 4px 16px rgba(74, 144, 226, 0.2);
        }
        
        .prompt-mode-option input[type="radio"]:checked + .prompt-mode-label::before {
            transform: scaleY(1);
        }
        
        .prompt-mode-icon {
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #f5f7fa, #e8ecf1);
            border-radius: 10px;
            margin-right: 15px;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }
        
        .prompt-mode-icon i {
            font-size: 22px;
            color: #6b7280;
            transition: all 0.3s ease;
        }
        
        .prompt-mode-option input[type="radio"]:checked + .prompt-mode-label .prompt-mode-icon {
            background: linear-gradient(135deg, #4a90e2, #357abd);
            box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
        }
        
        .prompt-mode-option input[type="radio"]:checked + .prompt-mode-label .prompt-mode-icon i {
            color: #ffffff;
            transform: scale(1.1);
        }
        
        .prompt-mode-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        
        .prompt-mode-title {
            font-size: 15px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
        
        .prompt-mode-desc {
            font-size: 13px;
            color: #6b7280;
            line-height: 1.5;
        }
        
        .prompt-mode-option input[type="radio"]:checked + .prompt-mode-label .prompt-mode-title {
            color: #4a90e2;
        }
        
        .prompt-mode-check {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transform: scale(0);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            flex-shrink: 0;
        }
        
        .prompt-mode-check i {
            font-size: 20px;
            color: #4a90e2;
        }
        
        .prompt-mode-option input[type="radio"]:checked + .prompt-mode-label .prompt-mode-check {
            opacity: 1;
            transform: scale(1);
        }
        
        @media (max-width: 768px) {
            .prompt-mode-selector {
                flex-direction: column;
            }
            
            .prompt-mode-option {
                min-width: 100%;
            }
        }
        </style>

        <p for="customer_prompt" class="ft-note"><i class="fa-solid fa-lightbulb"></i> Prompt : access code : %%title%% , %%lang%%, %%blog%%, %%cate%%, %%content%%</p>
        <input type="hidden" id="aiautotool_original_prompt_content" value="">

        <!-- Single Prompt Mode (Option 1) -->
        <div id="single_prompt_mode">
          <textarea id="aiautotool_prompt" name="aiautotool_prompt" class="ft-code-textarea" rows="5" style="height:200px" placeholder="Enter Prompt"><?php echo esc_html($artcle_prompt); ?></textarea>
         <p for="customer_prompt" class="ft-note">
            <i class="fa-solid fa-lightbulb"></i> Select Your Prompts in List: 
            <?php 
            if ($is_prompt_active) {
                echo '<a href="' . esc_url(admin_url('post-new.php?post_type=aiautotool_prompts')) . '" class="button">' . esc_html(__('Add Prompt','ai-auto-tool')) . '</a>';
            } else {
                echo '<a href="#" class="button aiautotool-prompt-inactive-link" style="opacity: 0.6; cursor: not-allowed;" title="' . esc_attr__('Please activate Prompt Manager feature to use this function', 'ai-auto-tool') . '">' . esc_html(__('Add Prompt','ai-auto-tool')) . '</a>';
            }
            ?>
         </p>
         <?php if (!$is_prompt_active): ?>
            <div class="notice notice-warning inline" style="margin: 10px 0; padding: 10px;">
                <p><strong><?php esc_html_e('Notice:', 'ai-auto-tool'); ?></strong> <?php esc_html_e('Prompt Manager feature is not active. Please activate it in settings to use prompts.', 'ai-auto-tool'); ?></p>
            </div>
         <?php endif; ?>
                                        <select id="customer_prompt" name="customer_prompt" class="prompt-single-select" <?php echo !$is_prompt_active ? 'disabled' : ''; ?>>
                                            <option value=""><?php esc_html_e('Select Prompt', 'ai-auto-tool'); ?></option>
                                            <?php
                                            if ($is_prompt_active) {
                                                $args = array(
                                                    'post_type' => 'aiautotool_prompts',
                                                    'posts_per_page' => -1,
                                                    'post_status' => 'publish',
                                                );
                                                $prompts = new WP_Query($args);
                                                if ($prompts->have_posts()) {
                                                    while ($prompts->have_posts()) {
                                                        $prompts->the_post();
                                                        ?>
                                                        <option value="<?php the_ID(); ?>"><?php the_title(); ?></option>
                                                        <?php
                                                    }
                                                    wp_reset_postdata();
                                                }
                                            }
                                            ?>
                                        </select>
                                        
                                        <style>
                                        .prompt-single-select {
                                            width: 100% !important;
                                            padding: 12px 40px 12px 16px !important;
                                            border: 2px solid #e0e0e0 !important;
                                            border-radius: 8px !important;
                                            background: #ffffff url('data:image/svg+xml;charset=UTF-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="%236b7280" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>') no-repeat right 12px center !important;
                                            background-size: 20px !important;
                                            font-size: 14px !important;
                                            color: #1f2937 !important;
                                            cursor: pointer !important;
                                            transition: all 0.3s ease !important;
                                            appearance: none !important;
                                            -webkit-appearance: none !important;
                                            -moz-appearance: none !important;
                                        }
                                        
                                        .prompt-single-select:hover {
                                            border-color: #4a90e2 !important;
                                        }
                                        
                                        .prompt-single-select:focus {
                                            outline: none !important;
                                            border-color: #4a90e2 !important;
                                            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1) !important;
                                        }
                                        
                                        .prompt-single-select option {
                                            padding: 10px !important;
                                            background: #ffffff !important;
                                        }
                                        
                                        .prompt-single-select:disabled {
                                            background: #f5f5f5 !important;
                                            cursor: not-allowed !important;
                                            opacity: 0.6 !important;
                                        }
                                        </style>
        </div>

        <!-- Multiple Prompts Mode (Option 2) -->
        <div id="multiple_prompts_mode" style="display: none;">
         <p for="customer_prompts_multiple" class="ft-note">
            <i class="fa-solid fa-lightbulb"></i> <?php esc_html_e('Select Multiple Prompts (hold Ctrl/Cmd to select multiple):', 'ai-auto-tool'); ?>
            <?php 
            if ($is_prompt_active) {
                echo '<a href="' . esc_url(admin_url('post-new.php?post_type=aiautotool_prompts')) . '" class="button">' . esc_html(__('Add Prompt','ai-auto-tool')) . '</a>';
            } else {
                echo '<a href="#" class="button aiautotool-prompt-inactive-link" style="opacity: 0.6; cursor: not-allowed;" title="' . esc_attr__('Please activate Prompt Manager feature to use this function', 'ai-auto-tool') . '">' . esc_html(__('Add Prompt','ai-auto-tool')) . '</a>';
            }
            ?>
         </p>
         <?php if (!$is_prompt_active): ?>
            <div class="notice notice-warning inline" style="margin: 10px 0; padding: 10px;">
                <p><strong><?php esc_html_e('Notice:', 'ai-auto-tool'); ?></strong> <?php esc_html_e('Prompt Manager feature is not active. Please activate it in settings to use prompts.', 'ai-auto-tool'); ?></p>
            </div>
         <?php endif; ?>
                                        <select id="customer_prompts_multiple" name="customer_prompts_multiple[]" multiple size="5" class="prompt-multiple-select" <?php echo !$is_prompt_active ? 'disabled' : ''; ?>>
                                            <?php
                                            if ($is_prompt_active) {
                                                $args = array(
                                                    'post_type' => 'aiautotool_prompts',
                                                    'posts_per_page' => -1,
                                                    'post_status' => 'publish',
                                                );
                                                $prompts = new WP_Query($args);
                                                if ($prompts->have_posts()) {
                                                    while ($prompts->have_posts()) {
                                                        $prompts->the_post();
                                                        ?>
                                                        <option value="<?php the_ID(); ?>"><?php the_title(); ?></option>
                                                        <?php
                                                    }
                                                    wp_reset_postdata();
                                                }
                                            }
                                            ?>
                                        </select>
                                        <p class="ft-note" style="margin-top: 8px; font-size: 12px; padding: 10px; background: #f0f7ff; border-left: 3px solid #4a90e2; border-radius: 4px;">
                                            <i class="fa-solid fa-info-circle" style="color: #4a90e2; margin-right: 6px;"></i> 
                                            <?php esc_html_e('Selected prompts will be randomly assigned to each post title. You can edit the content of each prompt below.', 'ai-auto-tool'); ?>
                                        </p>
                                        
                                        <!-- Container for multiple prompt textareas -->
                                        <div id="multiple_prompts_content" style="margin-top: 20px;"></div>
                                        
                                        <style>
                                        .prompt-multiple-select {
                                            width: 100% !important;
                                            min-height: 140px !important;
                                            padding: 12px !important;
                                            border: 2px solid #e0e0e0 !important;
                                            border-radius: 8px !important;
                                            background: #ffffff !important;
                                            font-size: 14px !important;
                                            line-height: 1.6 !important;
                                            transition: all 0.3s ease !important;
                                        }
                                        
                                        .prompt-multiple-select:focus {
                                            outline: none !important;
                                            border-color: #4a90e2 !important;
                                            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1) !important;
                                        }
                                        
                                        .prompt-multiple-select option {
                                            padding: 10px 12px !important;
                                            margin: 2px 0 !important;
                                            border-radius: 4px !important;
                                            cursor: pointer !important;
                                        }
                                        
                                        .prompt-multiple-select option:hover {
                                            background: #f0f7ff !important;
                                        }
                                        
                                        .prompt-multiple-select option:checked {
                                            background: linear-gradient(135deg, #4a90e2, #357abd) !important;
                                            color: #ffffff !important;
                                            font-weight: 600 !important;
                                        }
                                        
                                        .prompt-multiple-select:disabled {
                                            background: #f5f5f5 !important;
                                            cursor: not-allowed !important;
                                            opacity: 0.6 !important;
                                        }
                                        
                                        /* Multiple prompts textarea wrapper styles */
                                        .prompt-textarea-wrapper {
                                            border: 2px solid #e0e0e0;
                                            border-radius: 8px;
                                            padding: 15px;
                                            background: #ffffff;
                                            transition: all 0.3s ease;
                                        }
                                        
                                        .prompt-textarea-wrapper:hover {
                                            border-color: #4a90e2;
                                            box-shadow: 0 2px 8px rgba(74, 144, 226, 0.1);
                                        }
                                        
                                        .prompt-textarea-header {
                                            border-bottom: 1px solid #e0e0e0;
                                            padding-bottom: 8px;
                                            margin-bottom: 12px;
                                        }
                                        
                                        .prompt-content-textarea {
                                            width: 100% !important;
                                            border: 1px solid #d1d5db !important;
                                            border-radius: 6px !important;
                                            padding: 12px !important;
                                            font-family: 'Courier New', monospace !important;
                                            font-size: 13px !important;
                                            line-height: 1.6 !important;
                                            resize: vertical !important;
                                        }
                                        
                                        .prompt-content-textarea:focus {
                                            outline: none !important;
                                            border-color: #4a90e2 !important;
                                            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1) !important;
                                        }
                                        </style>
        </div>

        <!-- Auto Prompt Mode (Option 3) -->
        <div id="auto_prompt_mode" style="display: none;">
            <div style="padding: 20px; background: #f0f7ff; border-left: 3px solid #4a90e2; border-radius: 4px;">
                <p style="margin: 0 0 10px 0; font-weight: 600; color: #1f2937; font-size: 16px;">
                    <i class="fa-solid fa-magic" style="margin-right: 8px; color: #4a90e2;"></i>
                    <?php esc_html_e('Auto Prompt Mode', 'ai-auto-tool'); ?>
                </p>
                <p style="margin: 0; font-size: 14px; color: #6b7280; line-height: 1.6;">
                    <?php esc_html_e('The system will use generate_article_from_title function with auto prompt to generate content. No custom prompt is needed.', 'ai-auto-tool'); ?>
                </p>
            </div>
        </div>
                                        <div id="prompt_properties"></div>
                                         <script type="text/javascript">
                                            jQuery(document).ready(function($) {
        
        // Check if prompt manager is active
        var isPromptActive = <?php echo $is_prompt_active ? 'true' : 'false'; ?>;
        
        // Prevent click on Add Prompt link if inactive
        $('.aiautotool-prompt-inactive-link').on('click', function(e) {
            e.preventDefault();
            alert('<?php echo esc_js(__('Please activate Prompt Manager feature in settings to use this function.', 'ai-auto-tool')); ?>');
            return false;
        });
        
        // Handle mode switching
        $('input[name="prompt_selection_mode"]').change(function() {
            var mode = $(this).val();
            if (mode === 'single') {
                $('#single_prompt_mode').show();
                $('#multiple_prompts_mode').hide();
                $('#auto_prompt_mode').hide();
                // Clear multiple selection
                $('#customer_prompts_multiple').val([]);
            } else if (mode === 'multiple') {
                $('#single_prompt_mode').hide();
                $('#multiple_prompts_mode').show();
                $('#auto_prompt_mode').hide();
                // Clear single selection
                $('#customer_prompt').val('');
                $('#aiautotool_prompt').val('');
            } else if (mode === 'auto') {
                $('#single_prompt_mode').hide();
                $('#multiple_prompts_mode').hide();
                $('#auto_prompt_mode').show();
                // Clear all selections
                $('#customer_prompt').val('');
                $('#aiautotool_prompt').val('');
                $('#customer_prompts_multiple').val([]);
            }
        });
        
        // Single prompt selection (Option 1)
        $('#customer_prompt').change(function() {
            var selectedPrompt = $(this).val(); 

            // Check if prompt manager is active before loading
            if (!isPromptActive) {
                alert('<?php echo esc_js(__('Please activate Prompt Manager feature in settings to use prompts.', 'ai-auto-tool')); ?>');
                $(this).val('');
                return;
            }
            
            if (selectedPrompt) {
                $.ajax({
                    url: ajaxurl, 
                    type: 'POST',
                    data: {
                        action: 'aiautotool_load_customer_prompt_properties',
                        prompt_id: selectedPrompt
                    },
                    success: function(response) {
                        if(response.success){
                            var data = response.data;
                            console.log(data.prompt_content);
                            $('#aiautotool_prompt').val(data.prompt_content);
                            $('#aiautotool_original_prompt_content').val(data.prompt_content);
                             $('#prompt_properties').empty();
                        } else {
                            // Handle error response from server
                            var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('An error occurred while loading prompt.', 'ai-auto-tool')); ?>';
                            if (typeof aiautotool_alert_error !== 'undefined') {
                                aiautotool_alert_error(errorMsg);
                            } else {
                                alert(errorMsg);
                            }
                            $('#customer_prompt').val('');
                        }
                    },
                    error: function(xhr, status, error) {
                        var errorMsg = '<?php echo esc_js(__('An error occurred while loading properties.', 'ai-auto-tool')); ?>';
                        if (typeof aiautotool_alert_error !== 'undefined') {
                            aiautotool_alert_error(errorMsg);
                        } else {
                            alert(errorMsg);
                        }
                        $('#customer_prompt').val('');
                    }
                });
            } else {
                // Clear prompt textarea when no prompt selected
                $('#aiautotool_prompt').val('');
            }
        });
        
        // Store loaded prompts data
        var loadedPromptsData = {};
        
        // Handle multiple prompts selection (Option 2)
        $('#customer_prompts_multiple').on('change', function() {
            var selectedPrompts = $(this).val() || [];
            var container = $('#multiple_prompts_content');
            var currentPromptIds = container.find('.prompt-textarea-wrapper').map(function() {
                return $(this).data('prompt-id');
            }).get();
            
            // Remove textareas for unselected prompts
            container.find('.prompt-textarea-wrapper').each(function() {
                var promptId = $(this).data('prompt-id');
                if (selectedPrompts.indexOf(promptId) === -1) {
                    $(this).remove();
                    delete loadedPromptsData[promptId];
                }
            });
            
            // Add textareas for newly selected prompts
            selectedPrompts.forEach(function(promptId) {
                if (currentPromptIds.indexOf(promptId) === -1 && !loadedPromptsData[promptId]) {
                    // Load prompt content via AJAX
                    loadPromptContent(promptId);
                }
            });
        });
        
        // Function to load prompt content and create textarea
        function loadPromptContent(promptId) {
            if (!isPromptActive) {
                alert('<?php echo esc_js(__('Please activate Prompt Manager feature in settings to use prompts.', 'ai-auto-tool')); ?>');
                return;
            }
            
            // Get prompt title from select option
            var promptTitle = $('#customer_prompts_multiple option[value="' + promptId + '"]').text();
            
            // Show loading state
            var loadingHtml = '<div class="prompt-textarea-wrapper" data-prompt-id="' + promptId + '" style="margin-bottom: 20px;">' +
                '<div class="prompt-textarea-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; padding: 10px; background: #f5f7fa; border-radius: 6px;">' +
                '<label style="font-weight: 600; color: #1f2937; font-size: 14px;"><i class="fa-solid fa-file-lines" style="margin-right: 6px; color: #4a90e2;"></i>' + promptTitle + '</label>' +
                '<span class="prompt-loading" style="color: #6b7280; font-size: 12px;"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</span>' +
                '</div>' +
                '<textarea class="ft-code-textarea prompt-content-textarea" name="multiple_prompt_contents[]" data-prompt-id="' + promptId + '" rows="5" style="height:150px;" placeholder="Loading prompt content..."></textarea>' +
                '</div>';
            
            $('#multiple_prompts_content').append(loadingHtml);
            
            // Load prompt content via AJAX
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aiautotool_load_customer_prompt_properties',
                    prompt_id: promptId
                },
                success: function(response) {
                    if (response.success) {
                        var data = response.data;
                        var wrapper = $('#multiple_prompts_content .prompt-textarea-wrapper[data-prompt-id="' + promptId + '"]');
                        var textarea = wrapper.find('.prompt-content-textarea');
                        
                        // Set prompt content
                        textarea.val(data.prompt_content);
                        
                        // Store prompt data
                        loadedPromptsData[promptId] = {
                            content: data.prompt_content,
                            title: promptTitle
                        };
                        
                        // Remove loading indicator
                        wrapper.find('.prompt-loading').html('<i class="fa-solid fa-check-circle" style="color: #10b981;"></i> Loaded');
                        setTimeout(function() {
                            wrapper.find('.prompt-loading').fadeOut();
                        }, 1000);
                    } else {
                        var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('An error occurred while loading prompt.', 'ai-auto-tool')); ?>';
                        var wrapper = $('#multiple_prompts_content .prompt-textarea-wrapper[data-prompt-id="' + promptId + '"]');
                        wrapper.find('.prompt-loading').html('<span style="color: #ef4444;"><i class="fa-solid fa-exclamation-circle"></i> Error</span>');
                        wrapper.find('.prompt-content-textarea').val('').attr('placeholder', 'Error loading prompt content');
                        
                        if (typeof aiautotool_alert_error !== 'undefined') {
                            aiautotool_alert_error(errorMsg);
                        } else {
                            alert(errorMsg);
                        }
                    }
                },
                error: function(xhr, status, error) {
                    var errorMsg = '<?php echo esc_js(__('An error occurred while loading properties.', 'ai-auto-tool')); ?>';
                    var wrapper = $('#multiple_prompts_content .prompt-textarea-wrapper[data-prompt-id="' + promptId + '"]');
                    wrapper.find('.prompt-loading').html('<span style="color: #ef4444;"><i class="fa-solid fa-exclamation-circle"></i> Error</span>');
                    wrapper.find('.prompt-content-textarea').val('').attr('placeholder', 'Error loading prompt content');
                    
                    if (typeof aiautotool_alert_error !== 'undefined') {
                        aiautotool_alert_error(errorMsg);
                    } else {
                        alert(errorMsg);
                    }
                }
            });
        }
        
        // Clear multiple prompts when switching to single mode
        $('input[name="prompt_selection_mode"]').on('change', function() {
            if ($(this).val() === 'single') {
                $('#multiple_prompts_content').empty();
                loadedPromptsData = {};
            }
        });

    });

   

                                        </script>
        <?php
      
                    
                    
    }
    public static function register_prompt_cpt() {
        // Check if already registered to avoid duplicate registration
        if (post_type_exists('aiautotool_prompts')) {
            return;
        }
        
        $labels = [
            'name'               => __('Prompts', 'ai-auto-tool'),
            'singular_name'      => __('Prompt', 'ai-auto-tool'),
            'menu_name'          => __('Prompts', 'ai-auto-tool'),
            'name_admin_bar'     => __('Prompt', 'ai-auto-tool'),
            'add_new'            => __('Add New', 'ai-auto-tool'),
            'add_new_item'       => __('Add New Prompt', 'ai-auto-tool'),
            'new_item'           => __('New Prompt', 'ai-auto-tool'),
            'edit_item'          => __('Edit Prompt', 'ai-auto-tool'),
            'view_item'          => __('View Prompt', 'ai-auto-tool'),
            'all_items'          => __('All Prompts', 'ai-auto-tool'),
            'search_items'       => __('Search Prompts', 'ai-auto-tool'),
            'not_found'          => __('No Prompts found.', 'ai-auto-tool'),
            'not_found_in_trash' => __('No Prompts found in Trash.', 'ai-auto-tool'),
        ];

        $args = [
            'labels'             => $labels,
            'public'             => false,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => false, // Don't auto-create menu, we'll add it manually
            'query_var'          => true,
            'rewrite'            => ['slug' => 'aiautotool_prompts'],
            'capability_type'    => 'post',
            'has_archive'        => false, // Disable archive for private CPT
            'hierarchical'      => false,
            'menu_position'      => null,
            'menu_icon'          => 'dashicons-admin-post',
            'supports'           => ['title', 'editor'],
        ];

        register_post_type('aiautotool_prompts', $args);
        
        // Debug log if WP_DEBUG is enabled
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('AI Auto Tool: Prompt CPT registered successfully');
        }
    }
    public static function add_prompt_to_menu() {
        // Ensure parent menu exists
        if (!defined('MENUSUBPARRENT') || empty(MENUSUBPARRENT)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: MENUSUBPARRENT not defined');
            }
            return;
        }
        
        // Check if parent menu exists
        global $menu, $submenu;
        $parent_exists = false;
        $parent_slug = MENUSUBPARRENT;
        
        if (isset($menu)) {
            foreach ($menu as $menu_item) {
                if (isset($menu_item[2]) && $menu_item[2] === $parent_slug) {
                    $parent_exists = true;
                    break;
                }
            }
        }
        
        // Also check submenu (parent might be added as submenu)
        if (!$parent_exists && isset($submenu)) {
            if (isset($submenu[$parent_slug])) {
                $parent_exists = true;
            }
        }
        
        if (!$parent_exists) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: Parent menu ' . $parent_slug . ' does not exist');
                error_log('AI Auto Tool: Available menus: ' . print_r(array_keys($menu ?: array()), true));
            }
            // Try to add anyway - WordPress might create parent menu later
        }
        
        // Check if menu already exists to avoid duplicates
        $menu_exists = false;
        if (isset($submenu[$parent_slug])) {
            foreach ($submenu[$parent_slug] as $item) {
                if (isset($item[2]) && $item[2] === 'edit.php?post_type=aiautotool_prompts') {
                    $menu_exists = true;
                    break;
                }
            }
        }
        
        if ($menu_exists) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Auto Tool: Prompt menu already exists, skipping');
            }
            return;
        }
        
        // Add submenu
        $result = add_submenu_page(
            $parent_slug,       
            '<i class="fa-solid fa-link"></i> ' . __('Prompts Manager', 'ai-auto-tool'),          
            '<i class="fa-solid fa-link"></i> ' . __('Prompts Manager', 'ai-auto-tool'),         
            'manage_options',             
            'edit.php?post_type=aiautotool_prompts'
        );
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            if ($result) {
                error_log('AI Auto Tool: Prompt menu added successfully to ' . $parent_slug);
            } else {
                error_log('AI Auto Tool: Failed to add Prompt menu to ' . $parent_slug);
            }
        }
    }

    public function render_setting() {
        if($this->active!="true"){
            return '';
        }


    }

    public function render_tab_setting() {
        if($this->active=="true"){
            
        }
    }

    public function render_feature() {

       // Load feature descriptions
       require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
       
       $autoToolBox = new AutoToolBox(
           $this->icon.' '.$this->get_name_plan(),
           AiAutoTool_Feature_Descriptions::get('prompt_manager'),
           "https://doc.aiautotool.com/features/prompt-manager",
           $this->active_option_name,
           $this->active,
           plugins_url('../../images/logo.svg', __FILE__)
       );

        echo ($autoToolBox->generateHTML());
    }

    public static function add_metabox() {
        add_meta_box(
            'aiautotool_prompt_params',
            __('Prompt Parameters', 'ai-auto-tool'),
            [self::class, 'render_metabox'],
            'aiautotool_prompts',
            'normal',
            'high'
        );
    }

    public static function render_metabox($post) {
        wp_nonce_field('aiautotool_prompt_save_meta', 'aiautotool_prompt_meta_nonce');

        $params = get_post_meta($post->ID, '_aiautotool_prompt_params', true);
        
        echo '<div id="aiautotool-prompt-params-wrap">';
        if (!empty($params)) {
            foreach ($params as $param) {
                echo '<div class="aiautotool-prompt-param">';
                echo '<label>' . esc_html($param['label']) . '</label>';
                echo '<input type="text" name="aiautotool_prompt_params[]" value="' . esc_attr($param['value']) . '" />';
                echo '<select name="aiautotool_prompt_param_types[]">
                        <option value="input_text"' . selected($param['type'], 'input_text', false) . '>Input Text</option>
                        <option value="textarea"' . selected($param['type'], 'textarea', false) . '>Textarea</option>
                      </select><button type="button" class="aiautotool-remove-param button">Remove</button>';
                echo '</div>';
            }
        }
        echo '</div>';
        echo '<button type="button" id="aiautotool-add-param" class="button">' . esc_html(__('Add Parameter', 'ai-auto-tool')) . '</button>';
        ?>
        <script type="text/javascript">jQuery(document).ready(function ($) {
    let paramIndex = 0;

    $('#aiautotool-add-param').on('click', function () {
        paramIndex++;
        const newParam = `
            <div class="aiautotool-prompt-param">
                <label>Code : %code%</label>
                <input type="text" name="aiautotool_prompt_params[]" value="" placeholder="%title%" />
                <select name="aiautotool_prompt_param_types[]">
                    <option value="input_text">Input Text</option>
                    <option value="textarea">Textarea</option>
                </select>
                <button type="button" class="aiautotool-remove-param button">Remove</button>
            </div>
        `;
        $('#aiautotool-prompt-params-wrap').append(newParam);
    });

    $(document).on('click', '.aiautotool-remove-param', function () {
        $(this).closest('.aiautotool-prompt-param').remove();
    });
});
</script><?php
    }


    public static function save_metabox($post_id) {
        
       if (isset($_POST['aiautotool_prompt_meta_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aiautotool_prompt_meta_nonce'])), 'aiautotool_prompt_save_meta')) {
            
           
            if (isset($_POST['post_type']) && 'aiautotool_prompts' !== sanitize_text_field(wp_unslash($_POST['post_type']))) {
               
                return;
            }
            

            if (isset($_POST['aiautotool_prompt_params']) && isset($_POST['aiautotool_prompt_param_types'])) {
                
                if (is_array($_POST['aiautotool_prompt_params']) && is_array($_POST['aiautotool_prompt_param_types'])) {
                    $params = array();
                    $param_values = array_map('sanitize_text_field', wp_unslash($_POST['aiautotool_prompt_params']));
                    $param_types = array_map('sanitize_text_field', wp_unslash($_POST['aiautotool_prompt_param_types']));

                    
                    if (count($param_values) === count($param_types)) {
                        foreach ($param_values as $index => $value) {
                            $params[] = array(
                                'label' => $value,
                                'value' => $value,
                                'type' => isset($param_types[$index]) ? $param_types[$index] : '',
                            );
                        }

                        update_post_meta($post_id, '_aiautotool_prompt_params', $params);
                    } else {
                        
                    }
                } else {
                   
                }
            } else {
                
                delete_post_meta($post_id, '_aiautotool_prompt_params');
            }

                
            
        } else {
           
            return;
        }
    }

}
} // End of class_exists check
