<?php

/**
 * AI Magic Metabox - Modern Article Generator
 *
 * Provides a modern, minimalist article generation toolbar
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.0
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */
class AI_Magic_Metabox
{
    /**
     * Constructor - Register hooks
     *
     * @since    1.0.0
     */
    public function __construct()
    {
        add_action('add_meta_boxes', array($this, 'add_metabox'));
        add_action('admin_init', array($this, 'metabox_setup'));
        add_action('save_post', array($this, 'save_metabox'));

        // AJAX handlers
        add_action('wp_ajax_generate_ai_magic_content', array($this, 'generate_ai_magic_content_callback'));
        add_action('wp_ajax_generate_meta_description', array($this, 'generate_meta_description_callback'));
        add_action('wp_ajax_generate_keywords', array($this, 'generate_keywords_callback'));
        add_action('wp_ajax_save_meta_description', array($this, 'save_meta_description_callback'));
        add_action('wp_ajax_ai_magic_generate_image', array($this, 'generate_image_callback'));
        add_action('wp_ajax_ai_magic_preview_prompt', array($this, 'preview_prompt_callback'));
    }

    /**
     * Add metabox to post types
     *
     * @since    1.0.0
     */
    public function add_metabox()
    {
        // Get all public post types (including custom ones)
        $post_types = get_post_types(array('public' => true), 'names');

        // Remove attachments from the list
        unset($post_types['attachment']);

        foreach ($post_types as $post_type) {
            add_meta_box(
                'ai-magic-metabox',
                '✨ AI Magic - Content Generator',
                array($this, 'metabox_content'),
                $post_type,
                'normal',
                'high' // High priority to appear at top
            );
        }
    }

    /**
     * Setup metabox assets
     *
     * @since    1.0.0
     */
    public function metabox_setup()
    {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
    }

    /**
     * Render metabox content - Modern Minimalist Design
     *
     * @since    1.0.8
     * @param    WP_Post    $post    Current post object
     */
    public function metabox_content($post)
    {
        // Load required classes
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-templates.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-seo.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-history.php';

        // Get data
        $templates = Ai_Magic_Templates::get_templates();

        // Get active providers
        $active_providers = array();
        $providers = array('openai', 'anthropic', 'google', 'openrouter');
        foreach ($providers as $provider) {
            if (get_option("ai_magic_{$provider}_active", 'no') === 'yes') {
                $active_providers[] = $provider;
            }
        }
        if (empty($active_providers)) {
            $active_providers[] = 'openai'; // Default
        }

        // Get current provider
        $current_provider = isset($_COOKIE['ai_magic_current_provider']) ? sanitize_text_field($_COOKIE['ai_magic_current_provider']) : $active_providers[0];
        if (!in_array($current_provider, $active_providers)) {
            $current_provider = $active_providers[0];
        }
        ?>
        <div class="ai-magic-toolbar">
            <!-- Tabs Navigation -->
            <div class="ai-magic-tabs-nav">
                <button type="button" class="ai-magic-tab-btn active" data-tab="one-click">
                    🚀 <?php esc_html_e('Auto Generator', 'ai_magic'); ?>
                </button>
                <button type="button" class="ai-magic-tab-btn" data-tab="custom-generator" style="display:none;">
                    ✨ <?php esc_html_e('Advanced Generator', 'ai_magic'); ?>
                </button>
                <button type="button" class="ai-magic-tab-btn" data-tab="settings">
                    ⚙️ <?php esc_html_e('Settings', 'ai_magic'); ?>
                </button>
            </div>

            <!-- Tab Content: One-Click Full Article -->
            <div id="ai-magic-tab-one-click" class="ai-magic-tab-content active">
                <div class="ai-magic-one-click-section">
                    <div class="ai-magic-one-click-header">
                        <h4><?php esc_html_e('Generate Complete Article', 'ai_magic'); ?></h4>
                        <div class="ai-magic-header-actions">
                            <span id="ai-magic-detected-builder" class="ai-magic-badge" style="display:none;">
                                <span class="dashicons dashicons-admin-plugins"></span> <span class="builder-name"></span>
                            </span>
                            <button type="button" class="ai-magic-help-btn" id="ai-magic-one-click-help"
                                title="<?php esc_attr_e('How it works?', 'ai_magic'); ?>">
                                <span class="dashicons dashicons-editor-help"></span>
                            </button>
                        </div>
                    </div>
                    <div class="ai-magic-one-click-controls">
                        <textarea id="ai-magic-topic-input" class="ai-magic-topic-input"
                            placeholder="<?php esc_attr_e('Enter article topic or title... (e.g. How to create a website)', 'ai_magic'); ?>"
                            rows="1"></textarea>
                        <select id="ai-magic-word-count-full" class="ai-magic-select-compact">
                            <option value="500"><?php esc_html_e('Short (~500)', 'ai_magic'); ?></option>
                            <option value="1000"><?php esc_html_e('Medium (~1000)', 'ai_magic'); ?></option>
                            <option value="1500" selected><?php esc_html_e('Long (~1500)', 'ai_magic'); ?></option>
                            <option value="2000"><?php esc_html_e('Detailed (~2000)', 'ai_magic'); ?></option>
                        </select>
                        <button type="button" id="ai-magic-preview-full" class="ai-magic-btn-secondary"
                            title="<?php esc_attr_e('Preview Prompt', 'ai_magic'); ?>">
                            <span class="dashicons dashicons-visibility"></span>
                        </button>
                        <button type="button" id="ai-magic-generate-full" class="ai-magic-btn-large">
                            <span class="icon">🪄</span>
                            <span><?php esc_html_e('Fill Content', 'ai_magic'); ?></span>
                        </button>
                    </div>
                    <div class="ai-magic-one-click-options">
                        <label class="ai-magic-checkbox-label">
                            <input type="checkbox" id="ai-magic-auto-insert-all" checked>
                            <?php esc_html_e('Auto-fill all fields (Title, Content, SEO, Tags)', 'ai_magic'); ?>
                        </label>
                    </div>
                </div>
            </div>

            <!-- Tab Content: Custom Generator -->
            <div id="ai-magic-tab-custom-generator" class="ai-magic-tab-content">
                <!-- Quick Actions Buttons -->
                <div class="ai-magic-quick-actions">
                    <button type="button" id="ai-magic-generate-titles" class="ai-magic-quick-btn">
                        <span class="icon">📝</span>
                        <span><?php esc_html_e('Title Suggestions', 'ai_magic'); ?></span>
                    </button>
                    <button type="button" id="ai-magic-generate-outline" class="ai-magic-quick-btn">
                        <span class="icon">📋</span>
                        <span><?php esc_html_e('Create Outline', 'ai_magic'); ?></span>
                    </button>
                    <button type="button" id="ai-magic-improve-content" class="ai-magic-quick-btn">
                        <span class="icon">✨</span>
                        <span><?php esc_html_e('Improve', 'ai_magic'); ?></span>
                    </button>
                    <button type="button" id="ai-magic-check-seo" class="ai-magic-quick-btn">
                        <span class="icon">🔍</span>
                        <span><?php esc_html_e('SEO Check', 'ai_magic'); ?></span>
                    </button>
                </div>

                <!-- Main Toolbar -->
                <div class="ai-magic-main-bar">
                    <div class="ai-magic-logo">
                        <span class="ai-magic-logo-icon">✨</span>
                        <span>AI Magic</span>
                    </div>

                    <div class="ai-magic-input-area">
                        <input type="text" id="ai-magic-prompt-input" class="ai-magic-main-input"
                            placeholder="e.g., AI and Future, Healthy Eating Tips, WordPress SEO Guide..." value="">
                    </div>

                    <button type="button" id="ai-magic-preview-btn" class="ai-magic-icon-btn"
                        title="<?php esc_attr_e('Preview Prompt', 'ai_magic'); ?>" style="margin-right: 8px;">
                        <span class="dashicons dashicons-visibility"></span>
                    </button>

                    <button type="button" id="ai-magic-generate-btn" class="ai-magic-generate-btn">
                        <span class="icon">🚀</span>
                        <span><?php esc_html_e('Generate Article', 'ai_magic'); ?></span>
                    </button>
                </div>

                <!-- Quick Actions Bar -->
                <div class="ai-magic-actions-bar">


                    <!-- Quick Actions -->
                    <div class="ai-magic-action-group">
                        <button type="button" class="ai-magic-action-btn" data-action="meta">
                            <span class="icon">🔍</span>
                            <span><?php esc_html_e('Meta', 'ai_magic'); ?></span>
                        </button>
                        <button type="button" class="ai-magic-action-btn" data-action="keywords">
                            <span class="icon">🔑</span>
                            <span><?php esc_html_e('Keywords', 'ai_magic'); ?></span>
                        </button>
                        <button type="button" class="ai-magic-action-btn" data-action="image">
                            <span class="icon">🖼️</span>
                            <span><?php esc_html_e('Image', 'ai_magic'); ?></span>
                        </button>
                        <button type="button" class="ai-magic-action-btn" data-action="improve">
                            <span class="icon">✏️</span>
                            <span><?php esc_html_e('Improve', 'ai_magic'); ?></span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Tab Content: Settings -->
            <div id="ai-magic-tab-settings" class="ai-magic-tab-content">
                <!-- Advanced Options Panel -->
                <div class="ai-magic-options-panel" id="ai-magic-options-panel">

                    <!-- General Settings Group -->
                    <div class="ai-magic-settings-group">
                        <h4 class="ai-magic-group-title"><?php esc_html_e('General Settings', 'ai_magic'); ?></h4>
                        <div class="ai-magic-options-grid">
                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('AI Provider', 'ai_magic'); ?></label>
                                <select id="ai-magic-provider-select" class="ai-magic-option-input">
                                    <?php if (in_array('openai', $active_providers)): ?>
                                        <option value="openai" <?php selected($current_provider, 'openai'); ?>>OpenAI (GPT)</option>
                                    <?php endif; ?>
                                    <?php if (in_array('anthropic', $active_providers)): ?>
                                        <option value="anthropic" <?php selected($current_provider, 'anthropic'); ?>>Claude</option>
                                    <?php endif; ?>
                                    <?php if (in_array('google', $active_providers)): ?>
                                        <option value="google" <?php selected($current_provider, 'google'); ?>>Gemini</option>
                                    <?php endif; ?>
                                    <?php if (in_array('openrouter', $active_providers)): ?>
                                        <option value="openrouter" <?php selected($current_provider, 'openrouter'); ?>>OpenRouter
                                        </option>
                                    <?php endif; ?>
                                </select>
                            </div>

                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('Content Type', 'ai_magic'); ?></label>
                                <select id="ai-magic-template-select" class="ai-magic-option-input">
                                    <option value=""><?php esc_html_e('Blog Post', 'ai_magic'); ?></option>
                                    <?php foreach ($templates as $template): ?>
                                        <option value="<?php echo esc_attr($template->id); ?>">
                                            <?php echo esc_html($template->name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('Language', 'ai_magic'); ?></label>
                                <select id="ai-magic-language" class="ai-magic-option-input">
                                    <option value="en">🇬🇧 English</option>
                                    <option value="tr">🇹🇷 Turkish</option>
                                    <option value="es">🇪🇸 Spanish</option>
                                    <option value="fr">🇫🇷 French</option>
                                    <option value="de">🇩🇪 German</option>
                                    <option value="it">🇮🇹 Italian</option>
                                    <option value="pt">🇵🇹 Portuguese</option>
                                    <option value="ru">🇷🇺 Russian</option>
                                    <option value="ja">🇯🇵 Japanese</option>
                                    <option value="zh">🇨🇳 Chinese</option>
                                    <option value="ar">🇸🇦 Arabic</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Style & Tone Group -->
                    <div class="ai-magic-settings-group">
                        <h4 class="ai-magic-group-title"><?php esc_html_e('Style & Tone', 'ai_magic'); ?></h4>
                        <div class="ai-magic-options-grid">
                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('Writing Style', 'ai_magic'); ?></label>
                                <select id="ai-magic-style" class="ai-magic-option-input">
                                    <option value="informative">📚 Informative</option>
                                    <option value="creative">🎨 Creative</option>
                                    <option value="persuasive">💡 Persuasive</option>
                                    <option value="descriptive">🖼️ Descriptive</option>
                                    <option value="narrative">📖 Narrative</option>
                                </select>
                            </div>

                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('Tone', 'ai_magic'); ?></label>
                                <select id="ai-magic-tone" class="ai-magic-option-input">
                                    <option value="professional">💼 Professional</option>
                                    <option value="casual">😊 Casual</option>
                                    <option value="friendly">🤝 Friendly</option>
                                    <option value="formal">🎩 Formal</option>
                                    <option value="enthusiastic">🎉 Enthusiastic</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Content Details Group -->
                    <div class="ai-magic-settings-group">
                        <h4 class="ai-magic-group-title"><?php esc_html_e('Content Details', 'ai_magic'); ?></h4>
                        <div class="ai-magic-options-grid">
                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('Word Count', 'ai_magic'); ?></label>
                                <select id="ai-magic-word-count" class="ai-magic-option-input">
                                    <option value="300">~300 words (Short)</option>
                                    <option value="500" selected>~500 words (Medium)</option>
                                    <option value="800">~800 words (Long)</option>
                                    <option value="1200">~1200 words (Detailed)</option>
                                    <option value="2000">~2000 words (Comprehensive)</option>
                                </select>
                            </div>

                            <div class="ai-magic-option-item">
                                <label class="ai-magic-option-label"><?php esc_html_e('Focus Keywords', 'ai_magic'); ?></label>
                                <input type="text" id="ai-magic-keywords" class="ai-magic-option-input"
                                    placeholder="<?php esc_attr_e('keyword1, keyword2, keyword3', 'ai_magic'); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Additional Context Group -->
                    <div class="ai-magic-settings-group">
                        <h4 class="ai-magic-group-title"><?php esc_html_e('Additional Context', 'ai_magic'); ?></h4>
                        <div class="ai-magic-options-grid">
                            <div class="ai-magic-option-item" style="grid-column: 1 / -1;">
                                <label
                                    class="ai-magic-option-label"><?php esc_html_e('Custom Instructions', 'ai_magic'); ?></label>
                                <input type="text" id="ai-magic-instructions" class="ai-magic-option-input"
                                    placeholder="<?php esc_attr_e('Any specific requirements...', 'ai_magic'); ?>">
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Progress Indicator (Shared) -->
            <div class="ai-magic-progress" id="ai-magic-progress" style="display: none;">
                <div class="ai-magic-progress-bar">
                    <div class="ai-magic-progress-fill" id="ai-magic-progress-fill"></div>
                </div>
                <div class="ai-magic-progress-status">
                    <span class="step" data-step="1">📝 <?php esc_html_e('Title', 'ai_magic'); ?></span>
                    <span class="step" data-step="2">📄 <?php esc_html_e('Content', 'ai_magic'); ?></span>
                    <span class="step" data-step="3">📋 <?php esc_html_e('Summary', 'ai_magic'); ?></span>
                    <span class="step" data-step="4">🏷️ <?php esc_html_e('Tags', 'ai_magic'); ?></span>
                    <span class="step" data-step="5">🔍 <?php esc_html_e('SEO', 'ai_magic'); ?></span>
                </div>
            </div>

            <!-- Loading State -->
            <div class="ai-magic-loading" id="ai-magic-loading">
                <div class="ai-magic-spinner"></div>
                <span class="ai-magic-loading-text"><?php esc_html_e('Generating content...', 'ai_magic'); ?></span>
            </div>

            <!-- Output Preview -->
            <div class="ai-magic-output" id="ai-magic-output">
                <div class="ai-magic-output-header">
                    <span class="ai-magic-output-title"><?php esc_html_e('Generated Content', 'ai_magic'); ?></span>
                    <div class="ai-magic-output-actions">
                        <button type="button" class="ai-magic-action-btn" id="ai-magic-insert-btn">
                            <span class="icon">📥</span>
                            <span><?php esc_html_e('Insert to Editor', 'ai_magic'); ?></span>
                        </button>
                        <button type="button" class="ai-magic-action-btn" id="ai-magic-copy-btn">
                            <span class="icon">📋</span>
                            <span><?php esc_html_e('Copy', 'ai_magic'); ?></span>
                        </button>
                        <button type="button" class="ai-magic-action-btn" id="ai-magic-regenerate-btn">
                            <span class="icon">🔄</span>
                            <span><?php esc_html_e('Regenerate', 'ai_magic'); ?></span>
                        </button>
                    </div>
                </div>
                <div class="ai-magic-output-content" id="ai-magic-output-content"></div>
            </div>

            <!-- Status Bar -->
            <div class="ai-magic-status-bar">
                <span id="ai-magic-status-text"><?php esc_html_e('Ready', 'ai_magic'); ?></span>
                <span id="ai-magic-cost-estimate" style="float: right; color: #666; font-size: 11px; margin-left: 10px;"
                    title="<?php esc_attr_e('Estimated cost based on selected model and max tokens', 'ai_magic'); ?>">
                    <?php esc_html_e('Est. Cost: $0.00', 'ai_magic'); ?>
                </span>
                <div class="ai-magic-status-item">
                    <span
                        class="ai-magic-status-dot <?php echo !empty(get_option('ai_magic_api_key_openai', get_option('ai_magic_api_key', ''))) ? '' : 'inactive'; ?>"></span>
                    <span><?php esc_html_e('API Connected', 'ai_magic'); ?></span>
                </div>
                <div class="ai-magic-status-item">
                    <span>📊 <?php echo number_format(Ai_Magic_History::get_count(get_current_user_id())); ?>
                        <?php esc_html_e('generations', 'ai_magic'); ?></span>
                </div>
                <div class="ai-magic-status-item">
                    <span>🔌 SEO: <?php echo esc_html(Ai_Magic_SEO::get_seo_plugin_name()); ?></span>
                </div>
                <div class="ai-magic-status-item">
                    <span>✏️ Editor: <span id="ai-magic-status-editor">Detecting...</span></span>
                </div>
            </div>
            <!-- Preview Modal -->
            <div id="ai-magic-preview-modal" class="ai-magic-modal" style="display:none;">
                <div class="ai-magic-modal-content">
                    <div class="ai-magic-modal-header">
                        <h3><?php esc_html_e('Prompt Preview', 'ai_magic'); ?></h3>
                        <button type="button" class="ai-magic-modal-close">&times;</button>
                    </div>
                    <div class="ai-magic-modal-body">
                        <div class="ai-magic-preview-section">
                            <label><?php esc_html_e('Prompt:', 'ai_magic'); ?></label>
                            <div id="ai-magic-preview-prompt" class="ai-magic-preview-box"></div>
                        </div>
                        <div class="ai-magic-preview-section">
                            <label><?php esc_html_e('Settings:', 'ai_magic'); ?></label>
                            <ul id="ai-magic-preview-settings" class="ai-magic-preview-list"></ul>
                        </div>
                    </div>
                    <div class="ai-magic-modal-footer">
                        <button type="button"
                            class="ai-magic-btn-secondary ai-magic-modal-close"><?php esc_html_e('Close', 'ai_magic'); ?></button>
                        <button type="button" id="ai-magic-preview-generate" class="ai-magic-generate-btn">
                            <span class="icon">🚀</span>
                            <span><?php esc_html_e('Generate Now', 'ai_magic'); ?></span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Help Modal -->
            <div id="ai-magic-help-modal" class="ai-magic-modal" style="display:none;">
                <div class="ai-magic-modal-content ai-magic-modal-large">
                    <div class="ai-magic-modal-header">
                        <h3><?php esc_html_e('How One-Click Full Article Works', 'ai_magic'); ?></h3>
                        <button type="button" class="ai-magic-modal-close">&times;</button>
                    </div>
                    <div class="ai-magic-modal-body">
                        <div class="ai-magic-help-section">
                            <h4>🚀 <?php esc_html_e('Intelligent Article Generation', 'ai_magic'); ?></h4>
                            <p><?php esc_html_e('The One-Click Full Article feature is designed to create comprehensive, SEO-optimized content in seconds. It handles everything from title creation to meta descriptions.', 'ai_magic'); ?>
                            </p>
                        </div>

                        <div class="ai-magic-help-section">
                            <h4>🏗️ <?php esc_html_e('Structure Preservation (New!)', 'ai_magic'); ?></h4>
                            <p><?php esc_html_e('This is a powerful feature for page builders like Elementor, Divi, or custom HTML layouts.', 'ai_magic'); ?>
                            </p>
                            <ul>
                                <li><strong><?php esc_html_e('How it works:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('If you paste existing HTML code or content with a specific structure into the "Enter article topic" input, the AI will detect it.', 'ai_magic'); ?>
                                </li>
                                <li><strong><?php esc_html_e('What it does:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('It will STRICTLY PRESERVE your HTML tags, classes, and IDs. It will not break your layout.', 'ai_magic'); ?>
                                </li>
                                <li><strong><?php esc_html_e('The Result:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('The AI intelligently inserts the new content into your existing containers, replacing placeholder text while keeping your design intact.', 'ai_magic'); ?>
                                </li>
                            </ul>
                        </div>

                        <div class="ai-magic-help-section">
                            <h4>⚡ <?php esc_html_e('The Process', 'ai_magic'); ?></h4>
                            <ol>
                                <li><strong><?php esc_html_e('Input:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('Enter a topic OR paste your HTML template.', 'ai_magic'); ?></li>
                                <li><strong><?php esc_html_e('Analysis:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('The AI analyzes the input for structure and context.', 'ai_magic'); ?>
                                </li>
                                <li><strong><?php esc_html_e('Generation:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('It generates a Title, Slug, Excerpt, SEO Keywords, Tags, Meta Description, and the Full Content.', 'ai_magic'); ?>
                                </li>
                                <li><strong><?php esc_html_e('Insertion:', 'ai_magic'); ?></strong>
                                    <?php esc_html_e('If "Auto-fill all fields" is checked, it automatically populates all WordPress fields.', 'ai_magic'); ?>
                                </li>
                            </ol>
                        </div>
                    </div>
                    <div class="ai-magic-modal-footer">
                        <button type="button"
                            class="ai-magic-btn-primary ai-magic-modal-close"><?php esc_html_e('Got it!', 'ai_magic'); ?></button>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    public function save_metabox($post_id)
    {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return $post_id;

        if (isset($_POST['ai-magic-content'])) {
            update_post_meta($post_id, 'ai_magic_content', sanitize_text_field($_POST['ai-magic-content']));
        }
    }

    public function enqueue_assets($hook)
    {
        global $post;

        if ($hook == 'post-new.php' || $hook == 'post.php') {
            wp_enqueue_style('ai-magic-metabox', plugin_dir_url(__FILE__) . 'css/ai-magic-metabox.css', array(), '2.0.2');

            // Enqueue jQuery UI Autocomplete
            wp_enqueue_script('jquery-ui-autocomplete');
            // Enqueue jQuery UI CSS (optional, but good for basic styling if not present)
            // WordPress doesn't bundle a full jQuery UI CSS, so we might need to add some basic styles in our CSS or rely on admin styles.

            wp_enqueue_script('ai-magic-metabox', plugin_dir_url(__FILE__) . 'js/ai-magic-metabox.js', array('jquery', 'jquery-ui-autocomplete'), null, true);

            // Get user's prompt history
            $user_id = get_current_user_id();
            $prompt_history = get_user_meta($user_id, 'ai_magic_prompt_history', true);
            if (!is_array($prompt_history)) {
                $prompt_history = array();
            }

            // Get user's topic history
            $topic_history = get_user_meta($user_id, 'ai_magic_topic_history', true);
            if (!is_array($topic_history)) {
                $topic_history = array();
            }

            // Pass nonce and history to JavaScript
            // Get default provider
            $default_provider = AI_Magic_Provider_Manager::get_default_provider();

            // Get saved settings for the default provider
            $saved_language = get_option("ai_magic_{$default_provider}_language", 'en');
            $saved_style = get_option("ai_magic_{$default_provider}_style", 'informative');
            $saved_tone = get_option("ai_magic_{$default_provider}_tone", 'professional');
            $saved_model = get_option("ai_magic_{$default_provider}_model", '');

            wp_localize_script('ai-magic-metabox', 'aiMagicMetabox', array(
                'nonce' => wp_create_nonce('ai_magic_metabox_nonce'),
                'promptHistory' => array_values($prompt_history),
                'topicHistory' => array_values($topic_history),
                'defaultProvider' => $default_provider,
                'defaultLanguage' => $saved_language,
                'defaultStyle' => $saved_style,
                'defaultTone' => $saved_tone,
                'defaultModel' => $saved_model
            ));
        }
    }

    public function generate_ai_magic_content_callback()
    {
        // Verify nonce for CSRF protection
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ai_magic_metabox_nonce')) {
            wp_send_json_error('Security check failed');
            wp_die();
        }

        // Check user permissions - users should be able to edit posts
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
            wp_die();
        }

        if (isset($_POST['ai_magic_content'])) {
            // AI Magic Content'i alın
            $ai_magic_content = sanitize_text_field($_POST['ai_magic_content']);

            // Check user permissions or nonce here if needed

            if (isset($_POST['ai_magic_try_text'])) {

                $ai_magic_try_text = sanitize_textarea_field($_POST['ai_magic_try_text']);

                if (empty($ai_magic_try_text)) {
                    wp_send_json_error(['message' => 'Invalid prompt', 'text' => '', 'data' => null]);
                    wp_die();
                }

                // Save prompt to history
                $user_id = get_current_user_id();
                $prompt_history = get_user_meta($user_id, 'ai_magic_prompt_history', true);
                if (!is_array($prompt_history)) {
                    $prompt_history = array();
                }

                // Add new prompt if not exists
                if (!in_array($ai_magic_try_text, $prompt_history)) {
                    array_unshift($prompt_history, $ai_magic_try_text); // Add to beginning
                    $prompt_history = array_slice($prompt_history, 0, 50); // Keep last 50
                    update_user_meta($user_id, 'ai_magic_prompt_history', $prompt_history);
                }

                $provider_id = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';
                $provider_instance = AI_Magic_Provider_Manager::get_provider_instance($provider_id);

                if (!$provider_instance) {
                    wp_send_json_error(['message' => 'Invalid provider', 'text' => '']);
                    wp_die();
                }

                $response = (object) $provider_instance->generateText($ai_magic_try_text);

                if ($response->type == 'error') {
                    wp_send_json_error(['message' => 'Error while generating text', 'text' => esc_html($response->message)]);
                }
                // Send a success response
                wp_send_json_success([
                    'message' => 'Generating text successfully',
                    'text' => esc_html($response->message),
                    'data' => $response->data,
                    'raw_text' => isset($response->raw_text) ? $response->raw_text : ''
                ]);
            } else {
                // Send an error response if needed
                wp_send_json_error('Error while generating text');
            }

            wp_die();
        }
    }

    /**
     * Generate meta description via AJAX
     *
     * @since    1.0.7
     */
    public function generate_meta_description_callback()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ai_magic_metabox_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
        $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';

        if (empty($title)) {
            wp_send_json_error('Title is required');
        }

        $provider_id = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';
        $provider_instance = AI_Magic_Provider_Manager::get_provider_instance($provider_id);

        if (!$provider_instance) {
            wp_send_json_error('Invalid provider');
        }

        $response = $provider_instance->generateMetaDescription($title, $content);

        if ($response['type'] === 'success') {
            // Save to database if post_id provided
            if ($post_id > 0) {
                Ai_Magic_SEO::update_meta_description($post_id, $response['data']);
            }

            wp_send_json_success(array(
                'meta_description' => $response['data'],
                'length' => $response['length'],
                'message' => 'Meta description generated successfully!'
            ));
        } else {
            wp_send_json_error($response['message']);
        }
    }

    /**
     * Generate keywords via AJAX
     *
     * @since    1.0.7
     */
    public function generate_keywords_callback()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ai_magic_metabox_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';

        if (empty($content)) {
            wp_send_json_error('Content is required to extract keywords');
        }

        $provider_id = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';
        $provider_instance = AI_Magic_Provider_Manager::get_provider_instance($provider_id);

        if (!$provider_instance) {
            wp_send_json_error('Invalid provider');
        }

        $response = $provider_instance->generateFocusKeywords($content, 5);

        if ($response['type'] === 'success') {
            wp_send_json_success(array(
                'keywords' => $response['data'],
                'message' => 'Keywords extracted successfully!'
            ));
        } else {
            wp_send_json_error($response['message']);
        }
    }

    /**
     * Save meta description via AJAX
     *
     * @since    1.0.7
     */
    public function save_meta_description_callback()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ai_magic_metabox_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $meta_description = isset($_POST['meta_description']) ? sanitize_textarea_field($_POST['meta_description']) : '';

        if ($post_id <= 0) {
            wp_send_json_error('Invalid post ID');
        }

        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-seo.php';

        $result = Ai_Magic_SEO::update_meta_description($post_id, $meta_description);

        if ($result) {
            wp_send_json_success('Meta description saved successfully!');
        } else {
            wp_send_json_error('Failed to save meta description');
        }
    }
    /**
     * Preview prompt via AJAX
     *
     * @since    1.0.9
     */
    public function preview_prompt_callback()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ai_magic_metabox_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $prompt_text = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';

        if (empty($prompt_text)) {
            wp_send_json_error('Prompt is required');
        }

        // Prepare overrides
        $overrides = array(
            'language' => isset($_POST['language']) ? sanitize_text_field($_POST['language']) : '',
            'tone' => isset($_POST['tone']) ? sanitize_text_field($_POST['tone']) : '',
            'style' => isset($_POST['style']) ? sanitize_text_field($_POST['style']) : '',
            'word_count' => isset($_POST['word_count']) ? sanitize_text_field($_POST['word_count']) : '',
            'keywords' => isset($_POST['keywords']) ? sanitize_text_field($_POST['keywords']) : '',
            'instructions' => isset($_POST['instructions']) ? sanitize_text_field($_POST['instructions']) : ''
        );

        // Get selected provider or fallback to default
        $provider_id = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';

        if (!class_exists('AI_Magic_Provider_Manager')) {
            require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-provider-manager.php';
        }

        $provider = AI_Magic_Provider_Manager::get_provider_instance($provider_id);

        if (!$provider) {
            wp_send_json_error('Invalid provider selected: ' . $provider_id);
        }

        // Use the buildPrompt method via the interface
        $full_prompt = $provider->buildPrompt($prompt_text, $overrides);

        wp_send_json_success(array(
            'prompt' => $full_prompt,
            'message' => 'Prompt generated successfully!'
        ));
    }
}

$ai_magic_metabox = new AI_Magic_Metabox();
