<?php
// Fetch Posts Log UI Component
if ( ! defined( 'ABSPATH' ) ) exit;

// Get database access
global $wpdb;

// Get filter parameters
$filter_source = isset($_GET['feed']) ? intval($_GET['feed']) : 0;
$filter_status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';
$search_query = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
$per_page = 20;
$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Build query
$fetched_posts_table = $wpdb->prefix . 'blogibot_fetched_posts';
$feed_sources_table = $wpdb->prefix . 'blogibot_feed_sources';

$where_clauses = ['1=1'];
$query_params = [];

if ($filter_source > 0) {
    $where_clauses[] = 'fp.feed_source_id = %d';
    $query_params[] = $filter_source;
}

if (!empty($filter_status)) {
    $where_clauses[] = 'fp.import_status = %s';
    $query_params[] = $filter_status;
}

if (!empty($search_query)) {
    $where_clauses[] = '(fp.feed_item_title LIKE %s OR fs.feed_name LIKE %s)';
    $query_params[] = '%' . $wpdb->esc_like($search_query) . '%';
    $query_params[] = '%' . $wpdb->esc_like($search_query) . '%';
}

$where_sql = implode(' AND ', $where_clauses);

// Get total count
$total_query = "SELECT COUNT(*) FROM {$fetched_posts_table} fp 
                LEFT JOIN {$feed_sources_table} fs ON fp.feed_source_id = fs.id 
                WHERE {$where_sql}";
                
if (!empty($query_params)) {
    $total_count = $wpdb->get_var($wpdb->prepare($total_query, $query_params));
} else {
    $total_count = $wpdb->get_var($total_query);
}

// Get fetched posts data
$posts_query = "SELECT 
    fp.id,
    fp.feed_source_id,
    fp.post_id,
    fp.feed_item_title,
    fp.feed_item_url,
    fp.feed_item_date,
    fp.import_status,
    fp.import_date,
    fp.error_message,
    fp.created_at,
    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 {$where_sql}
ORDER BY fp.created_at DESC
LIMIT %d OFFSET %d";

$query_params[] = $per_page;
$query_params[] = $offset;

$fetched_posts = $wpdb->get_results($wpdb->prepare($posts_query, $query_params));

// Calculate statistics
$stats_query = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN import_status = 'imported' THEN 1 ELSE 0 END) as imported,
    SUM(CASE WHEN import_status = 'failed' THEN 1 ELSE 0 END) as failed,
    SUM(CASE WHEN import_status = 'duplicate' THEN 1 ELSE 0 END) as duplicate
FROM {$fetched_posts_table}";

$stats = $wpdb->get_row($stats_query);

// Ensure stats has default values if null
if (!$stats) {
    $stats = (object) [
        'total' => 0,
        'imported' => 0,
        'failed' => 0,
        'duplicate' => 0
    ];
} else {
    // Ensure all properties have default values
    $stats->total = $stats->total ?? 0;
    $stats->imported = $stats->imported ?? 0;
    $stats->failed = $stats->failed ?? 0;
    $stats->duplicate = $stats->duplicate ?? 0;
}

// Get all feed sources for filter dropdown
$feed_sources = $wpdb->get_results("SELECT id, feed_name FROM {$feed_sources_table} WHERE status = 'active' ORDER BY feed_name");

// Calculate pagination
$total_pages = ceil($total_count / $per_page);
$showing_from = $total_count > 0 ? $offset + 1 : 0;
$showing_to = min($offset + $per_page, $total_count);
?>
<div class="blog82ai-fetched-posts">
    <div class="blog82ai-page-header">
        <h2>Fetched Posts Log</h2>
        <p>View and manage imported posts from your feed sources</p>
    </div>

    <div class="blog82ai-header-actions">
        <button class="button button-primary" onclick="location.href='<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=add_feed_source')); ?>'">Add New Feed</button>
    </div>

    <!-- Filters and Search -->
    <form method="get" action="" class="blog82ai-posts-filters">
        <input type="hidden" name="page" value="blogibot">
        <input type="hidden" name="tab" value="feed">
        <input type="hidden" name="subtab" value="fetched_posts">
        
        <div class="blog82ai-filter-row">
            <div class="blog82ai-filter-group">
                <label for="filter-source">Source:</label>
                <select id="filter-source" name="feed" onchange="this.form.submit()">
                    <option value="">All Sources</option>
                    <?php foreach ($feed_sources as $source): ?>
                        <option value="<?php echo esc_attr($source->id); ?>" <?php selected($filter_source, $source->id); ?>>
                            <?php echo esc_html($source->feed_name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="blog82ai-filter-group">
                <label for="filter-status">Status:</label>
                <select id="filter-status" name="status" onchange="this.form.submit()">
                    <option value="">All Status</option>
                    <option value="imported" <?php selected($filter_status, 'imported'); ?>>Imported</option>
                    <option value="failed" <?php selected($filter_status, 'failed'); ?>>Failed</option>
                    <option value="duplicate" <?php selected($filter_status, 'duplicate'); ?>>Duplicate</option>
                </select>
            </div>
            <div class="blog82ai-filter-group">
                <input type="text" id="search-posts" name="s" value="<?php echo esc_attr($search_query); ?>" placeholder="Search posts...">
                <button type="submit" class="button">Search</button>
            </div>
        </div>
    </form>

    <!-- Posts Summary Stats -->
    <div class="blog82ai-posts-summary">
        <div class="blog82ai-summary-cards">
            <div class="blog82ai-summary-card">
                <div class="blog82ai-summary-number"><?php echo number_format($stats->total); ?></div>
                <div class="blog82ai-summary-label">Total Posts</div>
            </div>
            <div class="blog82ai-summary-card success">
                <div class="blog82ai-summary-number"><?php echo number_format($stats->imported); ?></div>
                <div class="blog82ai-summary-label">Successfully Imported</div>
                <div class="blog82ai-summary-change">
                    <?php echo $stats->total > 0 ? round(($stats->imported / $stats->total) * 100, 1) : 0; ?>% success rate
                </div>
            </div>
            <div class="blog82ai-summary-card warning">
                <div class="blog82ai-summary-number"><?php echo number_format($stats->duplicate); ?></div>
                <div class="blog82ai-summary-label">Duplicates Skipped</div>
                <div class="blog82ai-summary-change">
                    <?php echo $stats->total > 0 ? round(($stats->duplicate / $stats->total) * 100, 1) : 0; ?>% of attempts
                </div>
            </div>
            <div class="blog82ai-summary-card error">
                <div class="blog82ai-summary-number"><?php echo number_format($stats->failed); ?></div>
                <div class="blog82ai-summary-label">Failed Imports</div>
                <div class="blog82ai-summary-change">
                    <?php echo $stats->total > 0 ? round(($stats->failed / $stats->total) * 100, 1) : 0; ?>% error rate
                </div>
            </div>
        </div>
    </div>

    <!-- Posts Table -->
    <div class="blog82ai-posts-table">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th scope="col" class="manage-column">Post Title</th>
                    <th scope="col" class="manage-column">Feed Source</th>
                    <th scope="col" class="manage-column">Publish Date</th>
                    <th scope="col" class="manage-column">Import Date</th>
                    <th scope="col" class="manage-column">Status</th>
                    <th scope="col" class="manage-column">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($fetched_posts)): ?>
                <tr>
                    <td colspan="6" class="blog82ai-empty-state">
                        <p>No fetched posts found.</p>
                        <p>Posts will appear here once your feeds start importing content.</p>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($fetched_posts as $post): ?>
                <tr data-status="<?php echo esc_attr($post->import_status); ?>">
                    <td>
                        <strong>
                            <?php if ($post->post_id): ?>
                                <a href="<?php echo esc_url(admin_url('post.php?post=' . $post->post_id . '&action=edit')); ?>" target="_blank">
                                    <?php echo esc_html($post->feed_item_title); ?>
                                </a>
                            <?php else: ?>
                                <?php echo esc_html($post->feed_item_title); ?>
                            <?php endif; ?>
                        </strong>
                        <div class="row-actions">
                            <?php if ($post->post_id): ?>
                                <span class="view"><a href="<?php echo esc_url(get_permalink($post->post_id)); ?>" target="_blank">View Post</a> | </span>
                                <span class="edit"><a href="<?php echo esc_url(admin_url('post.php?post=' . $post->post_id . '&action=edit')); ?>" target="_blank">Edit</a> | </span>
                            <?php endif; ?>
                            <span class="source"><a href="<?php echo esc_url($post->feed_item_url); ?>" target="_blank">View Source</a></span>
                        </div>
                        <?php if ($post->import_status === 'failed' && !empty($post->error_message)): ?>
                        <div class="blog82ai-error-message">
                            <strong>Error:</strong> <?php echo esc_html($post->error_message); ?>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="blog82ai-source-name"><?php echo esc_html($post->feed_name); ?></span>
                        <div class="blog82ai-source-url">
                            <?php echo esc_html(parse_url($post->feed_url, PHP_URL_HOST)); ?>
                        </div>
                    </td>
                    <td>
                        <?php if ($post->feed_item_date): ?>
                            <span><?php echo esc_html(mysql2date('M j, Y', $post->feed_item_date)); ?></span>
                            <div class="blog82ai-datetime-secondary">
                                <?php echo esc_html(mysql2date('g:i A', $post->feed_item_date)); ?>
                            </div>
                        <?php else: ?>
                            <span class="blog82ai-na-text">N/A</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($post->import_date): ?>
                            <span><?php echo esc_html(mysql2date('M j, Y', $post->import_date)); ?></span>
                            <div class="blog82ai-datetime-secondary">
                                <?php echo esc_html(mysql2date('g:i A', $post->import_date)); ?>
                            </div>
                        <?php else: ?>
                            <span><?php echo esc_html(mysql2date('M j, Y', $post->created_at)); ?></span>
                            <div class="blog82ai-datetime-secondary">
                                <?php echo esc_html(mysql2date('g:i A', $post->created_at)); ?>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="blog82ai-status-badge status-<?php echo esc_attr($post->import_status); ?>">
                            <?php echo esc_html(ucfirst($post->import_status)); ?>
                        </span>
                    </td>
                    <td>
                        <div class="blog82ai-action-buttons">
                            <?php if ($post->post_id): ?>
                                <a href="<?php echo esc_url(admin_url('post.php?post=' . $post->post_id . '&action=edit')); ?>" 
                                   class="button button-small" title="Edit Post" target="_blank">✏️ Edit</a>
                            <?php endif; ?>
                            <a href="<?php echo esc_url($post->feed_item_url); ?>" 
                               class="button button-small" title="View Source" target="_blank">🔗 Source</a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="blog82ai-pagination">
        <div class="blog82ai-pagination-info">
            Showing <?php echo number_format($showing_from); ?>-<?php echo number_format($showing_to); ?> of <?php echo number_format($total_count); ?> posts
        </div>
        <div class="blog82ai-pagination-links">
            <?php
            $base_url = admin_url('admin.php?page=blogibot&tab=feed&subtab=fetched_posts');
            if ($filter_source) $base_url .= '&feed=' . $filter_source;
            if ($filter_status) $base_url .= '&status=' . urlencode($filter_status);
            if ($search_query) $base_url .= '&s=' . urlencode($search_query);
            
            // Previous button
            if ($current_page > 1): ?>
                <a href="<?php echo esc_url($base_url . '&paged=' . ($current_page - 1)); ?>" class="button">‹ Previous</a>
            <?php else: ?>
                <button class="button" disabled>‹ Previous</button>
            <?php endif; ?>
            
            <span class="blog82ai-page-numbers">
                <?php
                // Show first page
                if ($current_page > 3) {
                    echo '<a href="' . esc_url($base_url . '&paged=1') . '" class="button">1</a>';
                    if ($current_page > 4) echo '<span>...</span>';
                }
                
                // Show pages around current page
                $start = max(1, $current_page - 2);
                $end = min($total_pages, $current_page + 2);
                
                for ($i = $start; $i <= $end; $i++) {
                    if ($i == $current_page) {
                        echo '<button class="button button-primary">' . $i . '</button>';
                    } else {
                        echo '<a href="' . esc_url($base_url . '&paged=' . $i) . '" class="button">' . $i . '</a>';
                    }
                }
                
                // Show last page
                if ($current_page < $total_pages - 2) {
                    if ($current_page < $total_pages - 3) echo '<span>...</span>';
                    echo '<a href="' . esc_url($base_url . '&paged=' . $total_pages) . '" class="button">' . $total_pages . '</a>';
                }
                ?>
            </span>
            
            <?php
            // Next button
            if ($current_page < $total_pages): ?>
                <a href="<?php echo esc_url($base_url . '&paged=' . ($current_page + 1)); ?>" class="button">Next ›</a>
            <?php else: ?>
                <button class="button" disabled>Next ›</button>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>