<?php
// Generated Blog History UI (Dynamic Version)
if ( ! defined( 'ABSPATH' ) ) exit;

// Include the widgets class
require_once __DIR__ . '/GeneratedBlogHistoryWidgets.php';

// 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('image_regeneration');
$has_title_access = Blog82AI_License_Manager::has_feature_access('title_regeneration');
$has_content_access = Blog82AI_License_Manager::has_feature_access('content_regeneration');

// Enqueue CSS and JS
wp_enqueue_style('blog82ai-generated-blog-history', plugins_url('/assets/css/aiblog/blog82ai-generated-blog-history.css', dirname(dirname(dirname(__FILE__)))), [], '1.0.0');
wp_enqueue_script('blog82ai-generated-blog-history', plugins_url('/assets/js/aiblog/generated-blog-history.js', dirname(dirname(dirname(__FILE__)))), ['jquery'], '1.0.0', true);

// Localize script with nonces
wp_localize_script('blog82ai-generated-blog-history', 'blogHistoryData', [
    'ajaxNonce' => wp_create_nonce('blog82ai_ajax_nonce'),
    'regenerateNonce' => wp_create_nonce('regenerate_blog_title'),
    'contentRegenerateNonce' => wp_create_nonce('regenerate_blog_content')
]);

// Get dynamic statistics
$stats = Blog82AI_GeneratedBlogHistory_Widgets::get_blog_statistics();

// Get filter parameters
$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$per_page = 20;
$offset = ($current_page - 1) * $per_page;

$filters = [
    'category' => isset($_GET['filter_category']) ? sanitize_text_field($_GET['filter_category']) : '',
    'status' => isset($_GET['filter_status']) ? sanitize_text_field($_GET['filter_status']) : '',
    'date_range' => isset($_GET['filter_date']) ? sanitize_text_field($_GET['filter_date']) : '',
    'search' => isset($_GET['search_blogs']) ? sanitize_text_field($_GET['search_blogs']) : ''
];

// Get dynamic blog data
$blogs = Blog82AI_GeneratedBlogHistory_Widgets::get_all_generated_blogs($per_page, $offset, $filters);
$total_blogs = Blog82AI_GeneratedBlogHistory_Widgets::get_total_blogs_count($filters);
$total_pages = ceil($total_blogs / $per_page);

// Get categories for filter dropdown
$categories = Blog82AI_GeneratedBlogHistory_Widgets::get_generated_blog_categories();
?>
<div class="blog82ai-blog-history">
    <!-- Page header -->
    <div class="page-header">
        <h2>Generated Blogs History</h2>
        <p>View and manage AI-generated blog posts. Filter by category, status, and date.</p>
    </div>

    <!-- History Statistics moved to top -->
    <div class="blog82ai-history-stats">
        <h3>Blog Generation Statistics</h3>
        <div class="blog82ai-stats-grid">
            <div class="blog82ai-stat-card">
                <div class="stat-icon">📊</div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo $stats['total_blogs']; ?></div>
                    <div class="stat-label">Total Blogs Generated</div>
                    <div class="stat-trend">
                        <?php if ($stats['trend_percentage'] > 0): ?>
                            +<?php echo $stats['trend_percentage']; ?>% this month
                        <?php elseif ($stats['trend_percentage'] < 0): ?>
                            <?php echo $stats['trend_percentage']; ?>% this month
                        <?php else: ?>
                            No change this month
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="blog82ai-stat-card">
                <div class="stat-icon">✅</div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo $stats['published_blogs']; ?></div>
                    <div class="stat-label">Published Blogs</div>
                    <div class="stat-trend"><?php echo $stats['publish_rate']; ?>% publish rate</div>
                </div>
            </div>
            <div class="blog82ai-stat-card">
                <div class="stat-icon">📝</div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo $stats['draft_blogs']; ?></div>
                    <div class="stat-label">Draft Blogs</div>
                    <div class="stat-trend"><?php echo $stats['draft_rate']; ?>% draft rate</div>
                </div>
            </div>
            <div class="blog82ai-stat-card">
                <div class="stat-icon">🎯</div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo $stats['average_seo_score']; ?>%</div>
                    <div class="stat-label">Average SEO Score</div>
                    <div class="stat-trend">
                        <?php if ($stats['average_seo_score'] >= 80): ?>
                            Excellent performance
                        <?php elseif ($stats['average_seo_score'] >= 60): ?>
                            Good performance
                        <?php else: ?>
                            Needs improvement
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters and Search -->
    <div class="blog82ai-history-filters">
        <div class="filter-row">
            <div class="filter-group">
                <label for="filter-category">Category:</label>
                <select id="filter-category" name="filter_category">
                    <option value="">All Categories</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?php echo esc_attr($category->slug); ?>" 
                                <?php selected($filters['category'], $category->slug); ?>>
                            <?php echo esc_html($category->name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="filter-group">
                <label for="filter-status">Status:</label>
                <select id="filter-status" name="filter_status">
                    <option value="">All Status</option>
                    <option value="published" <?php selected($filters['status'], 'published'); ?>>Published</option>
                    <option value="draft" <?php selected($filters['status'], 'draft'); ?>>Draft</option>
                    <option value="future" <?php selected($filters['status'], 'future'); ?>>Scheduled</option>
                    <option value="trash" <?php selected($filters['status'], 'trash'); ?>>Trash</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filter-date">Date Range:</label>
                <select id="filter-date" name="filter_date">
                    <option value="">All Time</option>
                    <option value="today" <?php selected($filters['date_range'], 'today'); ?>>Today</option>
                    <option value="week" <?php selected($filters['date_range'], 'week'); ?>>This Week</option>
                    <option value="month" <?php selected($filters['date_range'], 'month'); ?>>This Month</option>
                    <option value="quarter" <?php selected($filters['date_range'], 'quarter'); ?>>This Quarter</option>
                </select>
            </div>
            <div class="filter-group search-group">
                <label for="search-blogs">Search:</label>
                <div class="search-input-wrapper">
                    <input type="text" id="search-blogs" name="search_blogs" 
                           placeholder="Search by title or content..." 
                           value="<?php echo esc_attr($filters['search']); ?>">
                    <button type="button" class="search-button" onclick="applyFilters()">Search</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Blog History Table -->
    <div class="blog82ai-history-table">
        <table class="blog82ai-blog-history-table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all-blogs"></th>
                    <th class="sortable">
                        <a href="#" onclick="sortTable('title')">Title</a>
                    </th>
                    <th>Category</th>
                    <th>Focus Keyphrase</th>
                    <th class="sortable">
                        <a href="#" onclick="sortTable('date')">Generated Date</a>
                    </th>
                    <th>Status</th>
                    <th>SEO Score</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($blogs)): ?>
                    <?php foreach ($blogs as $blog): ?>
                        <tr data-category="<?php echo esc_attr($blog['category_slug'] ?? 'uncategorized'); ?>" 
                            data-status="<?php echo esc_attr($blog['status']); ?>" 
                            data-date="<?php echo esc_attr(date('Y-m-d', strtotime($blog['generated_date']))); ?>">
                            <td>
                                <input type="checkbox" class="blog-checkbox" value="<?php echo $blog['id']; ?>">
                            </td>
                            <td>
                                <strong><a href="<?php echo $blog['edit_link']; ?>"><?php echo esc_html(wp_trim_words($blog['title'], 10)); ?></a></strong>
                                <div class="row-actions">
                                    <span class="edit"><a href="<?php echo $blog['edit_link']; ?>">Edit</a> | </span>
                                    <span class="view"><a href="<?php echo $blog['view_link']; ?>" target="_blank">
                                        <?php echo ($blog['status'] === 'publish') ? 'View' : 'Preview'; ?>
                                    </a></span>
                                    <?php if ($blog['status'] === 'draft'): ?>
                                        <span> | <a href="#publish-blog-<?php echo $blog['id']; ?>">Publish</a></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <?php 
                                if (!empty($blog['category'])) {
                                    echo esc_html($blog['category']);
                                } else {
                                    echo '<span style="color: #999;">Uncategorized</span>';
                                }
                                ?>
                            </td>
                            <td>
                                <?php 
                                echo $blog['focus_keyword'] ? esc_html($blog['focus_keyword']) : '<span style="color: #999;">Not set</span>';
                                ?>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($blog['generated_date'])); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo esc_attr($blog['status']); ?>">
                                    <?php 
                                    if ($blog['status'] === 'future') {
                                        echo 'SCHEDULED (' . date('M j', strtotime($blog['generated_date'])) . ')';
                                    } else {
                                        echo strtoupper($blog['status']);
                                    }
                                    ?>
                                </span>
                            </td>
                            <td>
                                <?php 
                                $seo_score = $blog['seo_score'];
                                $score_class = '';
                                if ($seo_score >= 90) $score_class = 'seo-excellent';
                                elseif ($seo_score >= 80) $score_class = 'seo-good';
                                elseif ($seo_score >= 70) $score_class = 'seo-average';
                                else $score_class = 'seo-poor';
                                ?>
                                <div class="seo-score <?php echo $score_class; ?>"><?php echo $seo_score; ?>%</div>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <?php if ($has_title_access): ?>
                                        <button class="button button-small" onclick="regenerateTitle(<?php echo $blog['id']; ?>)" title="Regenerate Title">🔄 Title</button>
                                    <?php else: ?>
                                        <button class="button button-small blog82ai-disabled-btn" disabled title="This feature is available only for paid users">🔄 Title <span class="blog82ai-pro-badge">PRO</span></button>
                                    <?php endif; ?>
                                    
                                    <?php if ($has_image_access): ?>
                                        <button class="button button-small" onclick="regenerateImage(<?php echo $blog['id']; ?>)" title="Regenerate Image">🖼️ Image</button>
                                    <?php else: ?>
                                        <button class="button button-small blog82ai-disabled-btn" disabled title="This feature is available only for paid users">🖼️ Image <span class="blog82ai-pro-badge">PRO</span></button>
                                    <?php endif; ?>
                                    
                                    <?php if ($has_content_access): ?>
                                        <button class="button button-small" onclick="regenerateContent(<?php echo $blog['id']; ?>)" title="Regenerate Content">📝 Content</button>
                                    <?php else: ?>
                                        <button class="button button-small blog82ai-disabled-btn" disabled title="This feature is available only for paid users">📝 Content <span class="blog82ai-pro-badge">PRO</span></button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="8" class="no-blogs-message">
                            <div class="empty-state">
                                <span class="dashicons dashicons-admin-post"></span>
                                <h3>No Generated Blogs Found</h3>
                                <p>Start creating AI-generated blogs to see them here.</p>
                                <a href="<?php echo admin_url('admin.php?page=blogibot-ai-blog'); ?>" 
                                   class="button button-primary">Create New Blog</a>
                            </div>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <div class="blog82ai-tablenav">
            <div class="alignleft">
                <select id="bulk-action-bottom">
                    <option value="">Bulk Actions</option>
                    <option value="publish">Publish</option>
                    <option value="draft">Move to Draft</option>
                    <option value="trash">Move to Trash</option>
                    <option value="regenerate-titles">Regenerate Titles</option>
                    <option value="regenerate-images">Regenerate Images</option>
                </select>
                <button class="button" onclick="applyBulkAction()">Apply</button>
            </div>
            <div class="blog82ai-tablenav-pages">
                <span class="displaying-num"><?php echo number_format($total_blogs); ?> items</span>
                <?php if ($total_pages > 1): ?>
                    <span class="blog82ai-pagination-links">
                        <?php if ($current_page > 1): ?>
                            <a class="button" href="?page=blogibot&tab=ai_blog&subtab=generated_blogs_history&paged=1<?php echo $query_string ?? ''; ?>">«</a>
                            <a class="button" href="?page=blogibot&tab=ai_blog&subtab=generated_blogs_history&paged=<?php echo ($current_page - 1); ?><?php echo $query_string ?? ''; ?>">‹</a>
                        <?php else: ?>
                            <span class="button disabled">«</span>
                            <span class="button disabled">‹</span>
                        <?php endif; ?>
                        
                        <span class="blog82ai-paging-input">
                            <input class="current-page" type="text" value="<?php echo $current_page; ?>" size="1">
                            <span class="blog82ai-tablenav-paging-text"> of <span class="total-pages"><?php echo $total_pages; ?></span></span>
                        </span>
                        
                        <?php if ($current_page < $total_pages): ?>
                            <a class="button" href="?page=blogibot&tab=ai_blog&subtab=generated_blogs_history&paged=<?php echo ($current_page + 1); ?><?php echo $query_string ?? ''; ?>">›</a>
                            <a class="button" href="?page=blogibot&tab=ai_blog&subtab=generated_blogs_history&paged=<?php echo $total_pages; ?><?php echo $query_string ?? ''; ?>">»</a>
                        <?php else: ?>
                            <span class="button disabled">›</span>
                            <span class="button disabled">»</span>
                        <?php endif; ?>
                    </span>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>