<?php
// Feed Dashboard UI (based on design template)
if ( ! defined( 'ABSPATH' ) ) exit;

global $wpdb;

// Get table names
$feed_sources_table = $wpdb->prefix . 'blogibot_feed_sources';
$fetched_posts_table = $wpdb->prefix . 'blogibot_fetched_posts';

// Get feed counts
$total_feeds = $wpdb->get_var("SELECT COUNT(*) FROM {$feed_sources_table}");
$active_feeds = $wpdb->get_var("SELECT COUNT(*) FROM {$feed_sources_table} WHERE status = 'active'");
$inactive_feeds = $total_feeds - $active_feeds;

// Get posts imported today
$today_start = date('Y-m-d 00:00:00');
$posts_today = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$fetched_posts_table} WHERE import_date >= %s",
    $today_start
));

// Get posts imported yesterday for comparison
$yesterday_start = date('Y-m-d 00:00:00', strtotime('-1 day'));
$yesterday_end = date('Y-m-d 23:59:59', strtotime('-1 day'));
$posts_yesterday = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$fetched_posts_table} WHERE import_date >= %s AND import_date <= %s",
    $yesterday_start,
    $yesterday_end
));

// Get posts this week
$week_start = date('Y-m-d 00:00:00', strtotime('-7 days'));
$posts_this_week = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$fetched_posts_table} WHERE import_date >= %s",
    $week_start
));

// Get posts last week for comparison
$last_week_start = date('Y-m-d 00:00:00', strtotime('-14 days'));
$last_week_end = date('Y-m-d 23:59:59', strtotime('-7 days'));
$posts_last_week = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$fetched_posts_table} WHERE import_date >= %s AND import_date <= %s",
    $last_week_start,
    $last_week_end
));

// Calculate import success rate
$total_attempts = $wpdb->get_var("SELECT COUNT(*) FROM {$fetched_posts_table}");
$successful_imports = $wpdb->get_var("SELECT COUNT(*) FROM {$fetched_posts_table} WHERE import_status = 'imported'");
$success_rate = $total_attempts > 0 ? round(($successful_imports / $total_attempts) * 100, 1) : 0;

// Calculate changes
$posts_today_change = $posts_today - $posts_yesterday;
$posts_week_change = $posts_this_week - $posts_last_week;
?>
<div class="blog82ai-feeds-dashboard">
    <!-- Dashboard Metrics -->
    <div class="blog82ai-dashboard-metrics">
        <div class="blog82ai-metric-card">
            <div class="blog82ai-metric-icon">📡</div>
            <div class="blog82ai-metric-content">
                <h3>Total Feeds Added</h3>
                <div class="blog82ai-metric-value"><?php echo number_format($total_feeds); ?></div>
                <div class="blog82ai-metric-change neutral"><?php echo $active_feeds; ?> active</div>
            </div>
        </div>

        <div class="blog82ai-metric-card">
            <div class="blog82ai-metric-icon">✅</div>
            <div class="blog82ai-metric-content">
                <h3>Active Feeds</h3>
                <div class="blog82ai-metric-value"><?php echo number_format($active_feeds); ?></div>
                <div class="blog82ai-metric-change neutral"><?php echo $inactive_feeds; ?> inactive</div>
            </div>
        </div>

        <div class="blog82ai-metric-card">
            <div class="blog82ai-metric-icon">📝</div>
            <div class="blog82ai-metric-content">
                <h3>Posts Imported Today</h3>
                <div class="blog82ai-metric-value"><?php echo number_format($posts_today); ?></div>
                <div class="blog82ai-metric-change <?php echo $posts_today_change >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $posts_today_change >= 0 ? '+' : ''; ?><?php echo $posts_today_change; ?> from yesterday
                </div>
            </div>
        </div>

        <div class="blog82ai-metric-card">
            <div class="blog82ai-metric-icon">📊</div>
            <div class="blog82ai-metric-content">
                <h3>Posts This Week</h3>
                <div class="blog82ai-metric-value"><?php echo number_format($posts_this_week); ?></div>
                <div class="blog82ai-metric-change <?php echo $posts_week_change >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $posts_week_change >= 0 ? '+' : ''; ?><?php echo $posts_week_change; ?> from last week
                </div>
            </div>
        </div>

        <div class="blog82ai-metric-card">
            <div class="blog82ai-metric-icon">🎯</div>
            <div class="blog82ai-metric-content">
                <h3>Import Success Rate</h3>
                <div class="blog82ai-metric-value"><?php echo $success_rate; ?>%</div>
                <div class="blog82ai-metric-change neutral"><?php echo number_format($successful_imports); ?> of <?php echo number_format($total_attempts); ?> succeeded</div>
            </div>
        </div>
    </div>

    <!-- Feed Activity Overview -->
    <?php
    // Get most active feeds by posts this week
    $active_feeds_data = $wpdb->get_results($wpdb->prepare("
        SELECT 
            fs.id,
            fs.feed_name,
            fs.feed_url,
            COUNT(fp.id) as post_count,
            MAX(fp.import_date) as last_import
        FROM {$feed_sources_table} fs
        LEFT JOIN {$fetched_posts_table} fp ON fs.id = fp.feed_source_id 
            AND fp.import_date >= %s
        WHERE fs.status = 'active'
        GROUP BY fs.id, fs.feed_name, fs.feed_url
        ORDER BY post_count DESC, last_import DESC
        LIMIT 4
    ", $week_start));
    
    $max_posts = 0;
    if (!empty($active_feeds_data)) {
        $max_posts = max(array_column($active_feeds_data, 'post_count'));
        if ($max_posts == 0) $max_posts = 1; // Avoid division by zero
    }
    ?>
    <div class="blog82ai-feed-activity">
        <h3>Recent Feed Activity</h3>
        <div class="blog82ai-activity-list">
            <?php if (empty($active_feeds_data)): ?>
                <div class="blog82ai-activity-item">
                    <div class="blog82ai-activity-content">
                        <div class="blog82ai-activity-title">No recent feed activity</div>
                        <div class="blog82ai-activity-time">Add feeds to see activity</div>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($active_feeds_data as $feed): ?>
                <div class="blog82ai-activity-item">
                    <div class="blog82ai-activity-icon status-success">✅</div>
                    <div class="blog82ai-activity-content">
                        <div class="blog82ai-activity-title">
                            <?php echo esc_html($feed->feed_name); ?> - 
                            <?php echo $feed->post_count; ?> post<?php echo $feed->post_count != 1 ? 's' : ''; ?> this week
                        </div>
                        <div class="blog82ai-activity-time">
                            <?php 
                            if ($feed->last_import) {
                                echo esc_html(human_time_diff(strtotime($feed->last_import), current_time('timestamp'))) . ' ago';
                            } else {
                                echo 'No recent imports';
                            }
                            ?>
                        </div>
                    </div>
                    <div class="blog82ai-activity-action">
                        <button class="button button-small" onclick="viewFeedPosts(<?php echo $feed->id; ?>)">View Posts</button>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Most Active Feed Sources -->
    <div class="blog82ai-dashboard-stats">
        <div class="blog82ai-stats-section">
            <h3>Most Active Feed Sources</h3>
            <div class="blog82ai-feed-stats">
                <?php if (empty($active_feeds_data)): ?>
                    <p style="color: #666; padding: 20px; text-align: center;">No feed data available yet.</p>
                <?php else: ?>
                    <?php foreach ($active_feeds_data as $feed): ?>
                    <div class="blog82ai-feed-item">
                        <div class="blog82ai-feed-info">
                            <span class="blog82ai-feed-name"><?php echo esc_html($feed->feed_name); ?></span>
                            <span class="blog82ai-feed-url"><?php echo esc_html(parse_url($feed->feed_url, PHP_URL_HOST)); ?></span>
                        </div>
                        <span class="blog82ai-feed-count"><?php echo $feed->post_count; ?> posts this week</span>
                        <div class="blog82ai-feed-bar">
                            <div class="blog82ai-feed-progress" style="width: <?php echo round(($feed->post_count / $max_posts) * 100); ?>%;"></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="blog82ai-stats-section">
            <h3>Import Statistics</h3>
            <div class="blog82ai-category-import-stats">
                <?php
                // Get import statistics by status
                $import_stats = $wpdb->get_results("
                    SELECT 
                        import_status,
                        COUNT(*) as count
                    FROM {$fetched_posts_table}
                    GROUP BY import_status
                    ORDER BY count DESC
                ");
                ?>
                <?php if (empty($import_stats)): ?>
                    <p style="color: #666; padding: 20px; text-align: center;">No import data available yet.</p>
                <?php else: ?>
                    <?php foreach ($import_stats as $stat): ?>
                    <div class="blog82ai-category-stat">
                        <span class="blog82ai-category-name"><?php echo esc_html(ucfirst($stat->import_status)); ?></span>
                        <span class="blog82ai-import-count"><?php echo number_format($stat->count); ?> imports</span>
                        <span class="blog82ai-success-rate">
                            <?php echo $total_attempts > 0 ? round(($stat->count / $total_attempts) * 100, 1) : 0; ?>%
                        </span>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- System Status -->
    <?php
    // Get last fetch time from most recent import
    $last_fetch = $wpdb->get_var("SELECT MAX(import_date) FROM {$fetched_posts_table}");
    $last_fetch_text = $last_fetch ? human_time_diff(strtotime($last_fetch), current_time('timestamp')) . ' ago' : 'Never';
    ?>
    <div class="blog82ai-system-status">
        <h3>Feed System Status</h3>
        <div class="blog82ai-status-items">
            <div class="blog82ai-status-item <?php echo $active_feeds > 0 ? 'status-success' : 'status-warning'; ?>">
                <span class="blog82ai-status-icon"><?php echo $active_feeds > 0 ? '✅' : '⚠️'; ?></span>
                <span class="blog82ai-status-text">Active Feeds: <?php echo $active_feeds; ?></span>
                <span class="blog82ai-status-detail">Last import: <?php echo $last_fetch_text; ?></span>
            </div>
            <div class="blog82ai-status-item status-success">
                <span class="blog82ai-status-icon">✅</span>
                <span class="blog82ai-status-text">Total Posts Imported: <?php echo number_format($total_attempts); ?></span>
                <span class="blog82ai-status-detail">Success rate: <?php echo $success_rate; ?>%</span>
            </div>
            <div class="blog82ai-status-item status-info">
                <span class="blog82ai-status-icon">ℹ️</span>
                <span class="blog82ai-status-text">Database Status: Active</span>
                <span class="blog82ai-status-detail"><?php echo number_format($total_feeds); ?> feeds configured</span>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="blog82ai-quick-navigation">
        <h3>Quick Actions</h3>
        <div class="blog82ai-nav-grid">
            <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=add_feed_source')); ?>" class="blog82ai-nav-item">
                <div class="blog82ai-nav-icon">➕</div>
                <div class="blog82ai-nav-title">Add New Feed</div>
                <div class="blog82ai-nav-description">Add a new RSS/Atom feed source</div>
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=manage_feeds')); ?>" class="blog82ai-nav-item">
                <div class="blog82ai-nav-icon">⚙️</div>
                <div class="blog82ai-nav-title">Manage Feeds</div>
                <div class="blog82ai-nav-description">Edit and configure existing feeds</div>
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=fetched_posts')); ?>" class="blog82ai-nav-item">
                <div class="blog82ai-nav-icon">📋</div>
                <div class="blog82ai-nav-title">Fetched Posts Log</div>
                <div class="blog82ai-nav-description">View imported posts and logs</div>
            </a>
        </div>
    </div>

    <!-- Recent Imports Preview -->
    <?php
    // Get recent imports
    $recent_imports = $wpdb->get_results("
        SELECT 
            fp.id,
            fp.post_id,
            fp.feed_item_title,
            fp.import_date,
            fp.import_status,
            fs.feed_name,
            fs.feed_url
        FROM {$fetched_posts_table} fp
        LEFT JOIN {$feed_sources_table} fs ON fp.feed_source_id = fs.id
        WHERE fp.import_status = 'imported' AND fp.post_id IS NOT NULL
        ORDER BY fp.import_date DESC
        LIMIT 5
    ");
    ?>
    <div class="blog82ai-recent-imports">
        <h3>Recent Imports</h3>
        <div class="blog82ai-imports-table">
            <table class="wp-list-table widefat">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Source</th>
                        <th>Import Time</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($recent_imports)): ?>
                    <tr>
                        <td colspan="4" style="text-align: center; padding: 20px; color: #666;">
                            No imports yet. Add feed sources to start importing posts.
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($recent_imports as $import): ?>
                        <tr>
                            <td>
                                <a href="<?php echo esc_url(admin_url('post.php?post=' . $import->post_id . '&action=edit')); ?>" target="_blank">
                                    <?php echo esc_html($import->feed_item_title); ?>
                                </a>
                            </td>
                            <td><?php echo esc_html($import->feed_name); ?></td>
                            <td><?php echo esc_html(human_time_diff(strtotime($import->import_date), current_time('timestamp'))) . ' ago'; ?></td>
                            <td>
                                <?php
                                $post_status = get_post_status($import->post_id);
                                $status_class = $post_status === 'publish' ? 'status-published' : 'status-draft';
                                $status_label = $post_status === 'publish' ? 'Published' : ucfirst($post_status);
                                ?>
                                <span class="blog82ai-status-badge <?php echo $status_class; ?>">
                                    <?php echo esc_html($status_label); ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="blog82ai-table-footer">
                <a href="<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=fetched_posts')); ?>" class="button">View All Imports</a>
            </div>
        </div>
    </div>
</div>

<script>
function viewFeedPosts(feedId) {
    window.location.href = `<?php echo admin_url('admin.php?page=blogibot&tab=feed&subtab=fetched_posts'); ?>&feed=${feedId}`;
}
</script>