<?php
// Generate New Blog component
if ( ! defined( 'ABSPATH' ) ) exit;

// Load License Manager
require_once WP_PLUGIN_DIR . '/blogibot/src/License/LicenseManager.php';

// Check user license type for feature access
$is_free_user = Blog82AI_License_Manager::is_free_user();
$has_image_access = Blog82AI_License_Manager::has_feature_access('featured_image');

// Enqueue CSS and JavaScript
wp_enqueue_style(
    'blog82ai-generate-new-blog-css',
    plugins_url('/assets/css/aiblog/blog82ai-generate-new-blog.css', dirname(dirname(dirname(__FILE__)))),
    array(),
    '1.0.0'
);

wp_enqueue_script(
    'blog82ai-generate-new-blog-js',
    plugins_url('/assets/js/aiblog/generate-new-blog/blog-generation.js', dirname(dirname(dirname(__FILE__)))),
    array('jquery'),
    '1.0.0',
    true
);

/**
 * Toastr Usage Examples:
 * 
 * PHP (Server-side - shows on next page load):
 * BlogiBotToastr::success('Blog saved successfully!');
 * BlogiBotToastr::error('Failed to save blog.');
 * BlogiBotToastr::warning('Please check your inputs.');
 * BlogiBotToastr::info('Blog generation started.');
 * 
 * JavaScript (Client-side - shows immediately):
 * window.BlogiToastr.success('Success message');
 * window.BlogiToastr.error('Error message');
 * window.BlogiToastr.warning('Warning message');
 * window.BlogiToastr.info('Info message');
 */
?>
<div class="blog82ai-generate-new-blog">
    <div class="page-header">
        <h2>Generate New Blog</h2>
        <p>Create AI-powered, SEO-optimized blog posts for your website</p>
    </div>

    <form class="blog82ai-blog-generation-form" id="blogGenerationForm">
        <?php wp_nonce_field('blogibot_generate_blog', 'nonce'); ?>
        <div class="form-section blog82ai-form-section">
            <h3 class="blog82ai-form-section-title">Basic Settings</h3>
            <div class="form-row">
                <div class="blog82ai-form-group">
                    <label for="blog82ai_category">Category *</label>
                    <select id="blog82ai_category" name="blog82ai_category" required>
                        <option value="">Select Category</option>
                        <?php
                        // Get categories with hierarchy
                        $categories = get_categories(array(
                            'hide_empty' => false,
                            'orderby' => 'name',
                            'order' => 'ASC'
                        ));
                        
                        // Function to display categories hierarchically
                        function display_category_hierarchy($categories, $parent_id = 0, $level = 0) {
                            foreach ($categories as $category) {
                                if ($category->parent == $parent_id) {
                                    // Create indentation based on level
                                    $indent = str_repeat('-', $level);
                                    if ($level > 0) {
                                        $indent .= ' ';
                                    }
                                    
                                    echo '<option value="' . esc_attr($category->name) . '" data-id="' . $category->term_id . '">' . 
                                         $indent . esc_html($category->name) . '</option>';
                                    
                                    // Recursively display child categories
                                    display_category_hierarchy($categories, $category->term_id, $level + 1);
                                }
                            }
                        }
                        
                        display_category_hierarchy($categories);
                        ?>
                    </select>
                </div>
                <div class="blog82ai-form-group">
                    <label for="blog82ai_language">Language *</label>
                    <select id="blog82ai_language" name="blog82ai_language" required>
                        <option value="English">English</option>
                        <option value="Spanish">Spanish</option>
                        <option value="French">French</option>
                        <option value="German">German</option>
                        <option value="Italian">Italian</option>
                        <option value="Portuguese">Portuguese</option>
                        <option value="Dutch">Dutch</option>
                        <option value="Chinese">Chinese</option>
                        <option value="Japanese">Japanese</option>
                        <option value="Korean">Korean</option>
                    </select>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="blog82ai_title">Blog Topic/Title (Optional)</label>
                <input type="text" id="blog82ai_title" name="blog82ai_title" placeholder="Leave empty for AI to generate based on category">
            </div>

            <div class="blog82ai-form-group">
                <label for="blog82ai_length">Content Length *</label>
                <select id="blog82ai_length" name="blog82ai_length" required>
                    <option value="Short (200-400 words)">Short (200-400 words)</option>
                    <option value="Medium (500-800 words)" selected>Medium (500-800 words)</option>
                    <option value="Long (900-1500 words)">Long (900-1500 words)</option>
                </select>
            </div>

            <div class="blog82ai-form-group">
                <label for="blog82ai_style">Writing Style *</label>
                <select id="blog82ai_style" name="blog82ai_style" required>
                    <option value="">-- Select Style --</option>
                    <option value="Formal">Formal</option>
                    <option value="Conversational">Conversational</option>
                    <option value="Technical">Technical</option>
                    <option value="Friendly">Friendly</option>
                </select>
            </div>
        </div>

        <div class="form-section blog82ai-form-section">
            <h3>SEO Settings</h3>
            <div class="blog82ai-form-group">
                <label for="blog82ai_keyphrase">Focus Keyphrase (Optional)</label>
                <input type="text" id="blog82ai_keyphrase" name="blog82ai_keyphrase" placeholder="e.g., WordPress development">
                <small>Primary keyword to optimize the blog post for</small>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="blog82ai_meta_title">Meta Title (Optional)</label>
                    <input type="text" id="blog82ai_meta_title" name="blog82ai_meta_title" placeholder="Auto-generated if empty" maxlength="60">
                    <small><span id="metaTitleCount">0</span>/60 characters</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="blog82ai_meta_description">Meta Description (Optional)</label>
                    <textarea id="blog82ai_meta_description" name="blog82ai_meta_description" placeholder="Auto-generated if empty" maxlength="160" rows="3"></textarea>
                    <small><span id="metaDescCount">0</span>/160 characters</small>
                </div>
            </div>
        </div>

        <div class="form-section blog82ai-form-section">
            <h3>Content Options</h3>
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group<?php echo $is_free_user ? ' blog82ai-disabled-feature' : ''; ?>">
                    <label<?php echo $is_free_user ? ' title="This feature is available only for paid users"' : ''; ?>>
                        <input type="checkbox" name="blog82ai_images" value="1" <?php echo $has_image_access ? 'checked' : 'disabled'; ?>>
                        Include images in blog content
                        <?php if ($is_free_user): ?>
                            <span class="blog82ai-premium-badge">PRO</span>
                        <?php endif; ?>
                    </label>
                    <small>Add relevant images within the blog post content</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="blog82ai_faq" value="1">
                        Include FAQ section
                    </label>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="blog82ai_conclusion" value="1" checked>
                        Include conclusion
                    </label>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="blog82ai_cta" value="1">
                        Include call-to-action
                    </label>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group<?php echo $is_free_user ? ' blog82ai-disabled-feature' : ''; ?>">
                    <label<?php echo $is_free_user ? ' title="This feature is available only for paid users"' : ''; ?>>
                        <input type="checkbox" id="blog82ai_featured_image" name="blog82ai_featured_image" value="1" <?php echo $is_free_user ? 'disabled' : ''; ?>>
                        Generate featured image with blog
                        <?php if ($is_free_user): ?>
                            <span class="blog82ai-premium-badge">PRO</span>
                        <?php endif; ?>
                    </label>
                    <small>Automatically generate a featured image based on the blog content</small>
                </div>
            </div>
        </div>

        <div class="form-section blog82ai-form-section">
            <h3>Publishing Options</h3>
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="blog82ai_post_status">Post Status</label>
                    <select id="blog82ai_post_status" name="blog82ai_post_status">
                        <option value="draft">Draft</option>
                        <option value="publish">Publish Immediately</option>
                        <option value="schedule">Schedule for Later</option>
                    </select>
                </div>
                <div class="blog82ai-form-group blog82ai-schedule-options" style="display: none;">
                    <label for="blog82ai_schedule_date">Schedule Date & Time</label>
                    <input type="datetime-local" id="blog82ai_schedule_date" name="blog82ai_schedule_date">
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="blog82ai_author">Author</label>
                <select id="blog82ai_author" name="blog82ai_author">
                    <?php
                    $current_user = wp_get_current_user();
                    $users = get_users(array('role__in' => array('administrator', 'editor', 'author')));
                    
                    echo '<option value="' . $current_user->ID . '" selected>' . esc_html($current_user->display_name) . ' (Current User)</option>';
                    
                    foreach ($users as $user) {
                        if ($user->ID != $current_user->ID) {
                            echo '<option value="' . $user->ID . '">' . esc_html($user->display_name) . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
        </div>

        <div class="blog82ai-form-actions">
            <button type="button" class="button" onclick="history.back()">Cancel</button>
            <button type="submit" class="button button-primary" id="generateBlogBtn">
                <span class="blog82ai-button-text">Generate Blog</span>
                <span class="button-spinner" style="display: none;">🔄</span>
            </button>
        </div>
    </form>

    <!-- Generation Progress -->
    <div class="generation-progress" id="generationProgress" style="display: none;">
        <div class="progress-content">
            <div class="progress-header">
                <div class="ai-icon">🧠</div>
                <h3>AI is generating your blog post...</h3>
                <p>Please wait while we create amazing content for you</p>
            </div>
            
            <div class="progress-steps">
                <div class="progress-step active">
                    <div class="step-icon">
                        <span class="step-number">1</span>
                        <div class="step-spinner"></div>
                    </div>
                    <div class="step-content">
                        <div class="step-text">Analyzing Topic & Keywords</div>
                        <div class="step-description">Understanding your content requirements</div>
                    </div>
                </div>
                <div class="progress-step">
                    <div class="step-icon">
                        <span class="step-number">2</span>
                        <div class="step-spinner"></div>
                    </div>
                    <div class="step-content">
                        <div class="step-text">Building Content Structure</div>
                        <div class="step-description">Creating outline and organizing ideas</div>
                    </div>
                </div>
                <div class="progress-step">
                    <div class="step-icon">
                        <span class="step-number">3</span>
                        <div class="step-spinner"></div>
                    </div>
                    <div class="step-content">
                        <div class="step-text">Writing Blog Content</div>
                        <div class="step-description">Generating engaging paragraphs</div>
                    </div>
                </div>
                <div class="progress-step">
                    <div class="step-icon">
                        <span class="step-number">4</span>
                        <div class="step-spinner"></div>
                    </div>
                    <div class="step-content">
                        <div class="step-text">SEO Optimization</div>
                        <div class="step-description">Enhancing for search engines</div>
                    </div>
                </div>
                <div class="progress-step">
                    <div class="step-icon">
                        <span class="step-number">5</span>
                        <div class="step-spinner"></div>
                    </div>
                    <div class="step-content">
                        <div class="step-text">Final Polish</div>
                        <div class="step-description">Adding finishing touches</div>
                    </div>
                </div>
                <div class="progress-step" id="imageGenerationStep" style="display: none;">
                    <div class="step-icon">
                        <span class="step-number">6</span>
                        <div class="step-spinner"></div>
                    </div>
                    <div class="step-content">
                        <div class="step-text">Generating Featured Image</div>
                        <div class="step-description">Creating AI-powered visual content</div>
                    </div>
                </div>
            </div>
            
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
            
            <div class="progress-footer">
                <div class="typing-indicator">
                    <span>AI is working</span>
                    <div class="typing-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
                <p class="progress-note">This usually takes 30-60 seconds</p>
                <p class="progress-note-image" id="progressNoteImage" style="display: none;">Featured image generation may take additional 15-30 seconds</p>
            </div>
        </div>
    </div>

    <!-- Generated Blog Result -->
    <div class="blog-result" id="blogResult" style="display: none;">
        <div class="result-header">
            <h3>✨ Your Blog Post is Ready!</h3>
            <button type="button" class="button" onclick="editBlog()">Edit Form</button>
        </div>
        
        <div class="blog-preview">
            <div class="blog-stats">
                <div class="stat-item">
                    <span class="stat-label">Word Count:</span>
                    <span class="stat-value" id="resultWordCount">-</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">Reading Time:</span>
                    <span class="stat-value" id="resultReadingTime">-</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">SEO Score:</span>
                    <span class="stat-value" id="resultSeoScore">-</span>
                </div>
            </div>
            
            <div class="blog-content">
                <h4 id="resultTitle">Blog Title</h4>
                <div class="blog-text" id="resultContent">Blog content will appear here...</div>
            </div>
            
            <!-- Featured Image Section (appears above SEO settings when image is generated) -->
            <div id="resultFeaturedImageSection" class="result-featured-image-section" style="display: none;">
                <div class="section-header">
                    <h4>Featured Image</h4>
                    <button type="button" class="button-link" onclick="showResultImageRegenerateForm()">
                        🔄 Change Image
                    </button>
                </div>
                
                <div class="featured-image-display">
                    <img id="resultFeaturedImageSrc" src="" alt="Featured Image" class="featured-img-result">
                    <div class="image-meta">
                        <span id="resultImageFileName">image.jpg</span>
                        <span id="resultImageSize">0 KB</span>
                    </div>
                </div>
                
                <!-- Image Regeneration Form -->
                <div id="resultImageRegenerateForm" class="result-image-regenerate-form" style="display: none;">
                    <div class="form-group">
                        <label for="resultCustomImagePrompt">Describe the image you want:</label>
                        <textarea id="resultCustomImagePrompt" placeholder="e.g., A modern office with people working on laptops, professional lighting"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="resultImageStyle">Style:</label>
                        <select id="resultImageStyle">
                            <option value="photorealistic">Photorealistic</option>
                            <option value="illustration">Illustration</option>
                            <option value="artistic">Artistic</option>
                            <option value="professional">Professional</option>
                        </select>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="button" onclick="hideResultImageRegenerateForm()">Cancel</button>
                        <button type="button" class="button button-primary" onclick="regenerateResultImage()">Generate New Image</button>
                    </div>
                </div>
            </div>
            
            <div class="seo-fields">
                <h4>SEO Settings</h4>
                <div class="seo-field">
                    <label for="resultMetaTitle">Meta Title:</label>
                    <input type="text" id="resultMetaTitle" class="regular-text">
                </div>
                <div class="seo-field">
                    <label for="resultMetaDescription">Meta Description:</label>
                    <textarea id="resultMetaDescription" rows="2" class="large-text"></textarea>
                </div>
                <div class="seo-field">
                    <label for="resultKeyphrase">Focus Keyphrase:</label>
                    <input type="text" id="resultKeyphrase" class="regular-text">
                </div>
            </div>
            
            <div class="blog-actions">
                <button type="button" class="button" onclick="showPreviewModal()">Preview Blog</button>
                <button type="button" class="button" onclick="saveDraft()">Save as Draft</button>
                <button type="button" class="button button-primary" onclick="publishPost()">Publish Now</button>
            </div>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div id="previewModal" class="blog82ai-modal" style="display: none;">
    <div class="blog82ai-modal-content">
        <div class="blog82ai-modal-header">
            <h3>Blog Preview</h3>
            <span class="blog82ai-modal-close" onclick="closePreviewModal()">&times;</span>
        </div>
        
        <div class="blog82ai-modal-body">
            <!-- Featured Image Section (appears above SEO settings when image is generated) -->
            <div id="previewFeaturedImageSection" class="preview-featured-image-section" style="display: none;">
                <div class="section-header">
                    <h4>Featured Image</h4>
                    <button type="button" class="button-link" onclick="showImageRegenerateForm()">
                        🔄 Change Image
                    </button>
                </div>
                
                <div class="featured-image-display">
                    <img id="previewFeaturedImageSrc" src="" alt="Featured Image" class="featured-img-preview">
                    <div class="image-meta">
                        <span id="previewImageFileName">image.jpg</span>
                        <span id="previewImageSize">0 KB</span>
                    </div>
                </div>
                
                <!-- Image Regeneration Form -->
                <div id="previewImageRegenerateForm" class="preview-image-regenerate-form" style="display: none;">
                    <div class="form-group">
                        <label for="previewCustomImagePrompt">Describe the image you want:</label>
                        <textarea id="previewCustomImagePrompt" placeholder="e.g., A modern office with people working on laptops, professional lighting"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="previewImageStyle">Style:</label>
                        <select id="previewImageStyle">
                            <option value="photorealistic">Photorealistic</option>
                            <option value="illustration">Illustration</option>
                            <option value="artistic">Artistic</option>
                            <option value="professional">Professional</option>
                        </select>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="button" onclick="hidePreviewImageRegenerateForm()">Cancel</button>
                        <button type="button" class="button button-primary" onclick="regeneratePreviewFeaturedImage()">Generate New Image</button>
                    </div>
                    
                    <!-- Progress indicator for regeneration -->
                    <div id="previewRegenerationProgress" style="display: none;">
                        <div class="regeneration-loading">
                            <div>🎨 Generating new image...</div>
                            <div class="loading-bar">
                                <div class="loading-fill"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- SEO Settings Preview -->
            <div class="seo-preview">
                <h4>SEO Settings</h4>
                <div class="seo-field">
                    <label>Meta Title:</label>
                    <div id="previewMetaTitle" class="preview-value">-</div>
                </div>
                <div class="seo-field">
                    <label>Meta Description:</label>
                    <div id="previewMetaDescription" class="preview-value">-</div>
                </div>
                <div class="seo-field">
                    <label>Focus Keyphrase:</label>
                    <div id="previewKeyphrase" class="preview-value">-</div>
                </div>
            </div>
            
            <!-- Blog Content Preview -->
            <div class="blog-content-preview">
                <h4 id="previewTitle">Blog Title</h4>
                <div id="previewContent" class="preview-blog-content">Blog content will appear here...</div>
            </div>
        </div>
    </div>
</div>
<?php
