<?php
// blog82ai-dashboard.php
// Dashboard UI for AI Blog module (ported from design)
if ( ! defined( 'ABSPATH' ) ) exit;

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

// Check license status
$license_valid = Blog82AI_License_Manager::is_license_valid();

// Determine current main tab and subtab
$current_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'license';
$current_subtab = isset($_GET['subtab']) ? sanitize_key($_GET['subtab']) : 'dashboard';

// Force license tab if license is not valid
if (!$license_valid && $current_tab !== 'license') {
    $current_tab = 'license';
}

// Define tabs and their subtabs
$main_tabs = [
    'license' => 'License',
    'ai_blog' => 'AI Blog'
];

// Icons for main tabs (Dashicons CSS classes)
$main_tab_icons = [
    'license' => 'dashicons-awards',
    'ai_blog' => 'dashicons-welcome-write-blog'
];

// The 'feed' tab is hidden in the current marketplace release.
// To enable it in a future release, define the constant `BLOGIBOT_ENABLE_FEED` = true
// (for example in the updated plugin entry-point or during release build).
if (defined('BLOGIBOT_ENABLE_FEED') && BLOGIBOT_ENABLE_FEED) {
    $main_tabs['feed'] = 'Feed';
    $main_tab_icons['feed'] = 'dashicons-rss';
} else {
    // If feed is disabled, prevent direct URL access to the feed tab
    if ($current_tab === 'feed') {
        $current_tab = 'license';
    }
}

$ai_blog_subtabs = [
    'dashboard'               => 'Dashboard',
    'generate_new_blog'       => 'Generate New Blog',
    'scheduled_blogs'         => 'Scheduled Blogs',
    'generated_blogs_history' => 'Generated Blogs History',
    'site_content_analyzer'   => 'Site Content Analyzer',
    'seo_settings'            => 'SEO Settings',
];

// Icons for AI Blog subtabs (dashicons)
$ai_subtab_icons = [
    'dashboard' => 'dashicons-dashboard',
    'generate_new_blog' => 'dashicons-edit',
    'scheduled_blogs' => 'dashicons-calendar',
    'generated_blogs_history' => 'dashicons-archive',
    'site_content_analyzer' => 'dashicons-search',
    'seo_settings' => 'dashicons-chart-area'
];

// Allow temporarily hiding the SEO Settings subtab via a constant so the change is reversible.
// Example: define('BLOGIBOT_HIDE_SEO_TAB', true);
if (defined('BLOGIBOT_HIDE_SEO_TAB') && BLOGIBOT_HIDE_SEO_TAB) {
    if (isset($ai_blog_subtabs['seo_settings'])) {
        unset($ai_blog_subtabs['seo_settings']);
    }
    $seo_tab_hidden = true;
} else {
    $seo_tab_hidden = false;
}

$feed_subtabs = [
    'dashboard'       => 'Dashboard',
    'add_feed_source' => 'Add Feed Source',
    'manage_feeds'    => 'Manage Feeds',
    'fetched_posts'   => 'Fetched Posts',
    // 'import_settings' => 'Import Settings', // Hidden - will be implemented in future version
];

// Icons for Feed subtabs (dashicons)
$feed_subtab_icons = [
    'dashboard' => 'dashicons-dashboard',
    'add_feed_source' => 'dashicons-plus-alt',
    'manage_feeds' => 'dashicons-admin-settings',
    'fetched_posts' => 'dashicons-list-view',
    // 'import_settings' => 'dashicons-admin-generic',
];
?>
<div class="blog82ai-wrap">
    <div style="margin-bottom: 10px;">
        <div>
            <h1 class="blog82ai-dashboard-title">Blogibot</h1>
            <p class="blog82ai-dashboard-subtitle">Smart AI for SEO-Ready Blog Creation & Feed Management</p>
        </div>
    </div>
    <div class="blog82ai-nav-tab-wrapper">
        <?php foreach ($main_tabs as $tab_key => $tab_label): ?>
            <?php 
            $tab_active = ($current_tab === $tab_key) ? 'blog82ai-nav-tab-active' : '';
            $tab_disabled = (!$license_valid && $tab_key !== 'license') ? 'blog82ai-nav-tab-disabled' : '';
            $tab_url = $tab_disabled ? '#' : admin_url('admin.php?page=blogibot&tab=' . $tab_key . '&subtab=dashboard');
            ?>
            <a href="<?php echo esc_url($tab_url); ?>" 
               class="blog82ai-nav-tab <?php echo $tab_active . ' ' . $tab_disabled; ?>"
               <?php if ($tab_disabled): ?>onclick="return false;" title="Please activate your license first"<?php endif; ?>>
                <?php $icon = $main_tab_icons[$tab_key] ?? ''; ?>
                <?php if ($icon): ?><span class="dashicons <?php echo esc_attr($icon); ?>" style="margin-right:8px; vertical-align:middle;"></span><?php endif; ?>
                <?php echo esc_html($tab_label); ?>
                <?php if (!$license_valid && $tab_key !== 'license'): ?>
                    <span class="dashicons dashicons-lock" style="font-size: 14px; margin-left: 5px;"></span>
                <?php endif; ?>
            </a>
        <?php endforeach; ?>
    </div>

    <?php if ($current_tab === 'license'): ?>
        <!-- License Tab Content -->
        <div class="blog82ai-nav-tab-content blog82ai-active">
            <div class="blog82ai-tab-content blog82ai-active">
                <?php include WP_PLUGIN_DIR . '/blogibot/src/License/License.php'; ?>
            </div>
        </div>
    <?php elseif ($current_tab === 'ai_blog' && $license_valid): ?>
        <!-- AI Blog Tab Content -->
        <div class="blog82ai-subtabs">
            <?php foreach ($ai_blog_subtabs as $key => $label): ?>
                <?php $active = ($current_subtab === $key) ? 'blog82ai-subtab-active' : ''; ?>
                <?php $icon = $ai_subtab_icons[$key] ?? ''; ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=' . $key)); ?>" class="blog82ai-subtab <?php echo $active; ?>">
                    <?php if ($icon): ?><span class="dashicons <?php echo esc_attr($icon); ?>" aria-hidden="true"></span><?php endif; ?>
                    <?php echo esc_html($label); ?>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="blog82ai-nav-tab-content blog82ai-active">
            <div class="blog82ai-tab-content blog82ai-active">
                <?php
                switch ($current_subtab) {
                    case 'generate_new_blog':
                        include WP_PLUGIN_DIR . '/blogibot/src/AIBlog/GenerateNewBlog/GenerateNewBlog.php';
                        break;
                    case 'scheduled_blogs':
                        include WP_PLUGIN_DIR . '/blogibot/src/AIBlog/ScheduledBlog/ScheduledBlog.php';
                        break;
                    case 'generated_blogs_history':
                        include WP_PLUGIN_DIR . '/blogibot/src/AIBlog/GeneratedBlogHistory/GeneratedBlogHistory.php';
                        break;
                    case 'site_content_analyzer':
                        include WP_PLUGIN_DIR . '/blogibot/src/AIBlog/SiteContentAnalyzer/SiteContentAnalyzer.php';
                        break;
                    case 'seo_settings':
                        include WP_PLUGIN_DIR . '/blogibot/src/AIBlog/SEOSetting/SEOSetting.php';
                        break;
                    case 'dashboard':
                    default:
                        // Load dashboard widgets class
                        require_once WP_PLUGIN_DIR . '/blogibot/src/AIBlog/Dashboard/DashboardWidgets.php';
                        
                        // Create sample data if in development mode and no data exists
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                            Blog82AI_Dashboard_Widgets::create_sample_data();
                        }
                        
                        // Get dashboard data
                        $metrics = Blog82AI_Dashboard_Widgets::get_metrics();
                        $categories = Blog82AI_Dashboard_Widgets::get_top_categories();
                        $keyphrases = Blog82AI_Dashboard_Widgets::get_top_keyphrases();
                        $system_status = Blog82AI_Dashboard_Widgets::get_system_status();
                        ?>
                        <div class="blog82ai-dashboard-metrics">
                        <div class="blog82ai-metric-card">
                            <div class="blog82ai-metric-icon">📝</div>
                            <div class="blog82ai-metric-title">TOTAL BLOGS GENERATED</div>
                            <div class="blog82ai-metric-value"><?php echo esc_html($metrics['total_blogs']); ?></div>
                            <div class="blog82ai-metric-note"><?php echo esc_html(Blog82AI_Dashboard_Widgets::format_metric_change($metrics['blogs_this_week'], $metrics['blogs_prev_week'], ' this week')); ?></div>
                        </div>
                        <div class="blog82ai-metric-card">
                            <div class="blog82ai-metric-icon">📅</div>
                            <div class="blog82ai-metric-title">BLOGS THIS WEEK</div>
                            <div class="blog82ai-metric-value"><?php echo esc_html($metrics['blogs_this_week']); ?></div>
                            <div class="blog82ai-metric-note"><?php echo esc_html(Blog82AI_Dashboard_Widgets::format_metric_change($metrics['blogs_this_week'], $metrics['blogs_prev_week'], ' from last week')); ?></div>
                        </div>
                        <div class="blog82ai-metric-card">
                            <div class="blog82ai-metric-icon">📊</div>
                            <div class="blog82ai-metric-title">BLOGS THIS MONTH</div>
                            <div class="blog82ai-metric-value"><?php echo esc_html($metrics['blogs_this_month']); ?></div>
                            <div class="blog82ai-metric-note"><?php echo esc_html(Blog82AI_Dashboard_Widgets::format_metric_change($metrics['blogs_this_month'], $metrics['blogs_prev_month'], ' from last month')); ?></div>
                        </div>
                        <div class="blog82ai-metric-card">
                            <div class="blog82ai-metric-icon">🎯</div>
                            <div class="blog82ai-metric-title">SEO SCORE AVERAGE</div>
                            <div class="blog82ai-metric-value"><?php echo esc_html($metrics['seo_score_avg']); ?>%</div>
                            <div class="blog82ai-metric-note">Based on AI-generated content</div>
                        </div>
                        <div class="blog82ai-metric-card">
                            <div class="blog82ai-metric-icon">⏰</div>
                            <div class="blog82ai-metric-title">ACTIVE SCHEDULES</div>
                            <div class="blog82ai-metric-value"><?php echo esc_html($metrics['active_schedules']); ?></div>
                            <div class="blog82ai-metric-note"><?php echo esc_html($metrics['paused_schedules']); ?> paused</div>
                        </div>
                    </div>
                    <div class="blog82ai-dashboard-rows">
                        <div class="blog82ai-dashboard-row">
                            <div class="blog82ai-dashboard-card">
                                <div class="blog82ai-dashboard-card-title">Categories with Most Blogs</div>
                                <div class="blog82ai-dashboard-list">
                                    <?php
                                    if (!empty($categories)) {
                                        $max_count = $categories[0]->post_count;
                                        foreach ($categories as $cat) {
                                            $percent = $max_count > 0 ? round(($cat->post_count / $max_count) * 100) : 0;
                                        ?>
                                        <div class="blog82ai-dashboard-list-item" style="display: flex; align-items: center; margin-bottom: 18px;">
                                            <span style="flex: 0 0 160px; min-width: 120px;"><?php echo esc_html($cat->name); ?></span>
                                            <div style="flex: 1; position: relative; height: 8px; margin: 0 12px; min-width: 80px;">
                                                <span class="blog82ai-dashboard-list-item-bar-bg" style="position: absolute; left: 0; right: 0; top: 0; height: 8px; width: 100%;"></span>
                                                <span class="blog82ai-dashboard-list-item-bar" style="position: absolute; left: 0; top: 0; height: 8px; width: <?php echo $percent; ?>%;"></span>
                                            </div>
                                            <span style="flex: 0 0 60px; min-width: 60px; text-align: right;"><?php echo esc_html($cat->post_count); ?> blogs</span>
                                        </div>
                                        <?php 
                                        }
                                    } else {
                                        echo '<p style="color: #666; font-style: italic;">No blog categories found yet. Start generating content to see statistics!</p>';
                                    }
                                    ?>
                                </div>
                            </div>
                            <div class="blog82ai-dashboard-card">
                                <div class="blog82ai-dashboard-card-title">Most Used Focus Keyphrases</div>
                                <div class="blog82ai-dashboard-list">
                                    <?php
                                    if (!empty($keyphrases)) {
                                        foreach ($keyphrases as $kp) {
                                        ?>
                                        <div class="blog82ai-dashboard-list-item" style="justify-content: space-between; align-items: center;">
                                            <span>"<?php echo esc_html($kp->meta_value); ?>"</span>
                                            <span class="blog82ai-pill"><?php echo esc_html($kp->usage_count); ?> times</span>
                                        </div>
                                        <?php 
                                        }
                                    } else {
                                        echo '<p style="color: #666; font-style: italic;">No focus keyphrases tracked yet. Generate content with SEO settings to see data!</p>';
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                        <div class="blog82ai-dashboard-row">
                            <div class="blog82ai-dashboard-card blog82ai-dashboard-card-status">
                                <div class="blog82ai-dashboard-card-title">System Status</div>
                                <div class="blog82ai-status-list">
                                    <div class="blog82ai-status-item blog82ai-status-<?php echo $system_status['api_connection'] === 'active' ? 'success' : 'warning'; ?>">
                                        <span class="blog82ai-status-icon blog82ai-status-icon-<?php echo $system_status['api_connection'] === 'active' ? 'success' : 'warning'; ?>">
                                            <?php echo $system_status['api_connection'] === 'active' ? '✔️' : '⚠️'; ?>
                                        </span>
                                        <span class="blog82ai-status-label">API Connection: <?php echo ucfirst($system_status['api_connection']); ?></span>
                                        <?php if ($system_status['api_connection'] !== 'active'): ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=license')); ?>" class="blog82ai-btn blog82ai-btn-small blog82ai-status-btn">Activate License</a>
                                        <?php endif; ?>
                                    </div>
                                    <div class="blog82ai-status-item blog82ai-status-<?php echo $system_status['domain_status'] === 'verified' ? 'success' : 'warning'; ?>">
                                        <span class="blog82ai-status-icon blog82ai-status-icon-<?php echo $system_status['domain_status'] === 'verified' ? 'success' : 'warning'; ?>">
                                            <?php echo $system_status['domain_status'] === 'verified' ? '✔️' : '⚠️'; ?>
                                        </span>
                                        <span class="blog82ai-status-label">Domain Status: <?php echo ucfirst($system_status['domain_status']); ?></span>
                                        <?php if ($system_status['domain_status'] !== 'verified'): ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=license')); ?>" class="blog82ai-btn blog82ai-btn-small blog82ai-status-btn">Activate License</a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="blog82ai-dashboard-row">
                            <div class="blog82ai-dashboard-card">
                                <div class="blog82ai-dashboard-card-title">Recent AI-Generated Blogs</div>
                                <div class="blog82ai-dashboard-list">
                                    <?php
                                    $recent_blogs = Blog82AI_Dashboard_Widgets::get_recent_blogs(5);
                                    if (!empty($recent_blogs)) {
                                        foreach ($recent_blogs as $blog) {
                                            $status_class = '';
                                            $status_text = '';
                                            switch ($blog->post_status) {
                                                case 'publish':
                                                    $status_class = 'success';
                                                    $status_text = 'Published';
                                                    break;
                                                case 'draft':
                                                    $status_class = 'warning';
                                                    $status_text = 'Draft';
                                                    break;
                                                case 'pending':
                                                    $status_class = 'info';
                                                    $status_text = 'Pending';
                                                    break;
                                            }
                                            $edit_url = admin_url('post.php?post=' . $blog->ID . '&action=edit');
                                        ?>
                                        <div class="blog82ai-dashboard-list-item" style="justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid #eee;">
                                            <div style="flex: 1;">
                                                <div style="font-weight: 600; margin-bottom: 4px;">
                                                    <a href="<?php echo esc_url($edit_url); ?>" style="text-decoration: none; color: #0073aa;">
                                                        <?php echo esc_html(wp_trim_words($blog->post_title, 8)); ?>
                                                    </a>
                                                </div>
                                                <div style="font-size: 12px; color: #666;">
                                                        <?php echo esc_html($blog->category_name ?: 'Uncategorized'); ?> • 
                                                        <?php 
                                                            $display_time = !empty($blog->generated_at) ? $blog->generated_at : $blog->post_date;
                                                            echo esc_html(human_time_diff(strtotime($display_time), current_time('timestamp')) . ' ago'); 
                                                        ?>
                                                </div>
                                            </div>
                                            <span class="blog82ai-pill blog82ai-pill-<?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                        </div>
                                        <?php 
                                        }
                                    } else {
                                        echo '<p style="color: #666; font-style: italic;">No AI-generated blogs found yet. <a href="' . esc_url(admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=generate_new_blog')) . '">Create your first blog!</a></p>';
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                        <div class="blog82ai-dashboard-row">
                            <div class="blog82ai-dashboard-card blog82ai-dashboard-card-actions">
                                <div class="blog82ai-dashboard-card-title">Quick Actions</div>
                                <div class="blog82ai-actions-list">
                                    <!-- Quick action links -->
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=generate_new_blog')); ?>" class="blog82ai-action-item">
                                        <div class="blog82ai-action-icon">✨</div>
                                        <div class="blog82ai-action-title">Generate New Blog</div>
                                        <div class="blog82ai-action-desc">Create a new AI-powered blog post</div>
                                    </a>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=scheduled_blogs')); ?>" class="blog82ai-action-item">
                                        <div class="blog82ai-action-icon">📅</div>
                                        <div class="blog82ai-action-title">Scheduled Blogs</div>
                                        <div class="blog82ai-action-desc">Manage your blog scheduling</div>
                                    </a>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=generated_blogs_history')); ?>" class="blog82ai-action-item">
                                        <div class="blog82ai-action-icon">🗂️</div>
                                        <div class="blog82ai-action-title">Blog History</div>
                                        <div class="blog82ai-action-desc">View and manage generated blogs</div>
                                    </a>
                                    <?php if (empty($seo_tab_hidden)): ?>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=seo_settings')); ?>" class="blog82ai-action-item">
                                        <div class="blog82ai-action-icon">🎯</div>
                                        <div class="blog82ai-action-title">SEO Settings</div>
                                        <div class="blog82ai-action-desc">Configure SEO optimization</div>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php
                    break;
            }
            ?>
        </div>
    </div>

    <?php elseif ($current_tab === 'feed' && $license_valid): ?>
        <!-- Feed Tab Content -->
        <div class="blog82ai-subtabs">
            <?php foreach ($feed_subtabs as $key => $label): ?>
                <?php 
                $active = ($current_subtab === $key) ? 'blog82ai-subtab-active' : ''; 
                $icon = $feed_subtab_icons[$key] ?? '';
                ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=' . $key)); ?>" class="blog82ai-subtab <?php echo $active; ?>">
                    <?php if ($icon): ?>
                        <span class="dashicons <?php echo esc_attr($icon); ?>" aria-hidden="true"></span>
                    <?php endif; ?>
                    <?php echo esc_html($label); ?>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="blog82ai-nav-tab-content blog82ai-active">
            <div class="blog82ai-tab-content blog82ai-active">
                <?php
                switch ($current_subtab) {
                    case 'add_feed_source':
                        include WP_PLUGIN_DIR . '/blogibot/src/Feed/AddFeedSource/AddFeedSource.php';
                        break;
                    case 'manage_feeds':
                        include WP_PLUGIN_DIR . '/blogibot/src/Feed/ManageFeedSource/ManageFeedSource.php';
                        break;
                    case 'fetched_posts':
                        include WP_PLUGIN_DIR . '/blogibot/src/Feed/FetchPostsLog/FetchPostsLog.php';
                        break;
                    // case 'import_settings':
                    //     include WP_PLUGIN_DIR . '/blogibot/src/Feed/ImportSettings/ImportSettings.php';
                    //     break;
                    case 'dashboard':
                    default:
                        include WP_PLUGIN_DIR . '/blogibot/src/Feed/Dashboard/Dashboard.php';
                        break;
                }
                ?>
            </div>
        </div>
    <?php endif; ?>
</div>
