<?php
/**
 * Partial: AI Training - Knowledge Base Cards View
 * Displays all available knowledge bases (vector stores) in a card grid.
 * Stats like document count and last update are loaded asynchronously via JavaScript.
 */

if (!defined('ABSPATH')) {
    exit;
}

use WPAICG\Vector\AIPKit_Vector_Store_Registry;

// --- NEW: Get general settings for filtering user uploads ---
$training_general_settings = get_option('aipkit_training_general_settings', ['hide_user_uploads' => true]);
$hide_user_uploads = $training_general_settings['hide_user_uploads'] ?? true;
// --- END NEW ---

$all_stores = [];
if (class_exists(AIPKit_Vector_Store_Registry::class)) {
    // OpenAI
    $openai_stores = AIPKit_Vector_Store_Registry::get_registered_stores_by_provider('OpenAI');
    if (is_array($openai_stores)) {
        foreach ($openai_stores as $store) {
            $store_name = isset($store['name']) ? (string) $store['name'] : (string) ($store['id'] ?? '');
            $is_user_upload = strpos($store_name, 'chat_file_') === 0;
            if ($hide_user_uploads && $is_user_upload) {
                continue;
            }
            $document_count = 'N/A';
            if (!empty($store['file_counts']['total'])) {
                $document_count = (int) $store['file_counts']['total'];
            }
            $all_stores[] = [
                'name' => $store_name,
                'id' => isset($store['id']) ? (string) $store['id'] : $store_name,
                'provider' => 'OpenAI',
                'is_user_upload' => $is_user_upload,
                'expires_at' => $store['expires_at'] ?? null,
                'document_count' => $document_count,
            ];
        }
    }
    // Pinecone
    $pinecone_indexes = AIPKit_Vector_Store_Registry::get_registered_stores_by_provider('Pinecone');
    if (is_array($pinecone_indexes)) {
        foreach ($pinecone_indexes as $index) {
            $name = isset($index['name']) ? (string) $index['name'] : (string) ($index['id'] ?? '');
            $document_count = !empty($index['total_vector_count']) ? (int) $index['total_vector_count'] : 'N/A';
            $all_stores[] = [
                'name' => $name,
                'id' => $name,
                'provider' => 'Pinecone',
                'is_user_upload' => false,
                'document_count' => $document_count,
            ];
        }
    }
    // Qdrant
    $qdrant_collections = AIPKit_Vector_Store_Registry::get_registered_stores_by_provider('Qdrant');
    if (is_array($qdrant_collections)) {
        foreach ($qdrant_collections as $collection) {
            $name = isset($collection['name']) ? (string) $collection['name'] : (string) ($collection['id'] ?? '');
            $document_count = !empty($collection['vectors_count']) ? (int) $collection['vectors_count'] : 'N/A';
            $all_stores[] = [
                'name' => $name,
                'id' => $name,
                'provider' => 'Qdrant',
                'is_user_upload' => false,
                'document_count' => $document_count,
            ];
        }
    }
}
// Compute last updated timestamp for each store from local DB to enable sorting by recency
global $wpdb;
if ($wpdb instanceof \wpdb && !empty($all_stores)) {
    $table_name = $wpdb->prefix . 'aipkit_vector_data_source';
    $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));
    foreach ($all_stores as &$store) {
        $store['last_updated_ts'] = 0;
        if ($table_exists === $table_name) {
            $last_updated_ts = $wpdb->get_var($wpdb->prepare(
                "SELECT MAX(timestamp) FROM {$table_name} WHERE provider = %s AND vector_store_id = %s",
                $store['provider'],
                $store['id']
            ));
            if ($last_updated_ts) {
                $ts_num = is_numeric($last_updated_ts) ? (int) $last_updated_ts : strtotime($last_updated_ts);
                if ($ts_num) {
                    $store['last_updated_ts'] = $ts_num;
                }
            }
        }
    }
    unset($store);
}

// Sort by last updated desc, then by name as a fallback
usort($all_stores, function ($a, $b) {
    $a_ts = (int)($a['last_updated_ts'] ?? 0);
    $b_ts = (int)($b['last_updated_ts'] ?? 0);
    if ($a_ts === $b_ts) {
        return strcasecmp($a['name'], $b['name']);
    }
    return $b_ts <=> $a_ts;
});

?>

<?php if (empty($all_stores)): ?>
    <?php include __DIR__ . '/vector-store/_empty-state.php'; ?>
<?php else: ?>
    <div class="aipkit_kb_card_grid" role="grid" aria-label="<?php esc_attr_e('Knowledge Base Cards', 'gpt3-ai-content-generator'); ?>">
        <?php foreach ($all_stores as $store):
            $provider_lower = strtolower($store['provider']);
            // Use flattened precomputed count to avoid undefined index notices
            $doc_count_display = isset($store['document_count']) ? $store['document_count'] : 'N/A';

            // Last updated from local DB (safe: check table exists)
            global $wpdb;
            $last_updated_display = 'N/A';
            if ($wpdb instanceof \wpdb) {
                $table_name = $wpdb->prefix . 'aipkit_vector_data_source';
                $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));
                if ($table_exists === $table_name) {
                    $last_updated_ts = $wpdb->get_var($wpdb->prepare(
                        "SELECT MAX(timestamp) FROM {$table_name} WHERE provider = %s AND vector_store_id = %s",
                        $store['provider'],
                        $store['id']
                    ));
                    if ($last_updated_ts) {
                        $ts_num = is_numeric($last_updated_ts) ? (int) $last_updated_ts : strtotime($last_updated_ts);
                        if ($ts_num) {
                            $last_updated_display = human_time_diff($ts_num, current_time('timestamp')) . ' ' . esc_html__('ago', 'gpt3-ai-content-generator');
                        }
                    }
                }
            }
        ?>
            <article class="aipkit_kb_card"
                     data-provider="<?php echo esc_attr($store['provider']); ?>"
                     data-id="<?php echo esc_attr($store['id']); ?>"
                     data-name="<?php echo esc_attr($store['name']); ?>"
                     data-last-updated-ts="<?php echo esc_attr($store['last_updated_ts'] ?? 0); ?>"
                     tabindex="0"
                     role="button"
                     aria-label="<?php echo esc_attr(sprintf(__('View details for %s knowledge base', 'gpt3-ai-content-generator'), $store['name'])); ?>">

                <div class="aipkit_kb_card_body">
                    <header class="aipkit_kb_card_body_header">
                        <h3 class="aipkit_kb_card_title"><?php echo esc_html($store['name']); ?></h3>
                        <div class="aipkit_kb_card_header_actions">
                            <span class="aipkit_kb_card_provider aipkit_provider_tag_<?php echo esc_attr($provider_lower); ?>"><?php echo esc_html($store['provider']); ?></span>
                            <?php if (!empty($store['is_user_upload'])): ?>
                                <span class="aipkit_kb_card_user_upload_badge" title="<?php esc_attr_e('User uploaded knowledge base from chat interface', 'gpt3-ai-content-generator'); ?>">
                                    <span class="dashicons dashicons-admin-users"></span>
                                    <?php esc_html_e('User', 'gpt3-ai-content-generator'); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </header>

                    <section class="aipkit_kb_card_stats" aria-label="<?php esc_attr_e('Knowledge base statistics', 'gpt3-ai-content-generator'); ?>">
                        <div class="aipkit_kb_card_stat">
                            <span class="aipkit_kb_card_stat_label"><?php esc_html_e('Documents', 'gpt3-ai-content-generator'); ?></span>
                <span class="aipkit_kb_card_stat_value" data-stat="doc-count" data-initialized="true" aria-live="polite"><?php echo is_numeric($doc_count_display) ? esc_html(number_format_i18n($doc_count_display)) : esc_html($doc_count_display); ?></span>
                        </div>
                        <div class="aipkit_kb_card_stat">
                            <span class="aipkit_kb_card_stat_label">
                                <?php 
                                // Show "Expires" for user uploads, "Updated" for regular stores
                                echo !empty($store['is_user_upload']) && !empty($store['expires_at']) 
                                    ? esc_html__('Expires', 'gpt3-ai-content-generator')
                                    : esc_html__('Updated', 'gpt3-ai-content-generator'); 
                                ?>
                            </span>
                <span class="aipkit_kb_card_stat_value" data-stat="<?php echo !empty($store['is_user_upload']) && !empty($store['expires_at']) ? 'expires' : 'last-updated'; ?>" aria-live="polite" <?php echo (empty($store['is_user_upload']) || empty($store['expires_at'])) ? 'data-initialized="true"' : ''; ?>>
                                <?php if (!empty($store['is_user_upload']) && !empty($store['expires_at'])): ?>
                                    <?php 
                                    $expires_timestamp = is_numeric($store['expires_at']) ? $store['expires_at'] : strtotime($store['expires_at']);
                                    echo esc_html(date_i18n(get_option('date_format'), $expires_timestamp));
                                    ?>
                                <?php else: ?>
                    <?php echo esc_html($last_updated_display); ?>
                                <?php endif; ?>
                            </span>
                        </div>
                    </section>
                </div>
                
                <footer class="aipkit_kb_card_footer">
                    <span><?php esc_html_e('Manage', 'gpt3-ai-content-generator'); ?></span>
                    <span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
                </footer>
            </article>
        <?php endforeach; ?>
    </div>
<?php endif; ?>