<?php
/**
 * Admin knowledge base page.
 *
 * @package Inqyra
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables from parent scope.

$admin = new Inqyra_Admin('inqyra', INQYRA_VERSION);
$agent = $admin->get_current_agent();

if (!$agent) {
    echo '<div class="wrap"><div class="notice notice-warning"><p>' . esc_html__('Please create an agent first.', 'inqyra') . '</p></div></div>';
    return;
}

global $wpdb;

// Get knowledge chunks statistics
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$chunks_by_type = $wpdb->get_results($wpdb->prepare(
    'SELECT content_type, COUNT(*) as count, SUM(needs_embedding) as pending
     FROM %i
     WHERE agent_id = %d
     GROUP BY content_type',
    $wpdb->prefix . 'inqyra_knowledge_chunks',
    $agent->id
));

// Get last crawl run
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$last_crawl = $wpdb->get_row($wpdb->prepare(
    'SELECT * FROM %i
     WHERE agent_id = %d
     ORDER BY created_at DESC
     LIMIT 1',
    $wpdb->prefix . 'inqyra_crawl_runs',
    $agent->id
));

// Pagination
$per_page = 20;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Standard WordPress pagination parameter.
$current_page = isset($_GET['paged']) ? max(1, intval(wp_unslash($_GET['paged']))) : 1;
$offset = ($current_page - 1) * $per_page;

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$total_chunks = $wpdb->get_var($wpdb->prepare(
    'SELECT COUNT(*) FROM %i WHERE agent_id = %d',
    $wpdb->prefix . 'inqyra_knowledge_chunks',
    $agent->id
));

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$chunks = $wpdb->get_results($wpdb->prepare(
    'SELECT * FROM %i
     WHERE agent_id = %d
     ORDER BY created_at DESC
     LIMIT %d OFFSET %d',
    $wpdb->prefix . 'inqyra_knowledge_chunks',
    $agent->id,
    $per_page,
    $offset
));

$total_pages = ceil($total_chunks / $per_page);

?>
<div class="wrap inqyra-admin">
    <h1><?php esc_html_e('Knowledge Base', 'inqyra'); ?></h1>

    <?php if (get_option('inqyra_upgrade_recrawl_needed')): ?>
        <div class="notice notice-info is-dismissible inqyra-upgrade-recrawl-notice" style="margin: 15px 0;">
            <p>
                <strong><?php esc_html_e('Premium activated!', 'inqyra'); ?></strong>
                <?php esc_html_e('Your free-version crawl only indexed pages. Re-crawl your site now to index posts, products, and custom post types, and re-process embeddings for the best results.', 'inqyra'); ?>
            </p>
            <p>
                <button type="button" class="button inqyra-dismiss-recrawl-notice" style="margin-left: 0;">
                    <?php esc_html_e('Dismiss', 'inqyra'); ?>
                </button>
            </p>
        </div>
    <?php endif; ?>

    <!-- Statistics -->
    <div class="inqyra-stats-grid">
        <?php foreach ($chunks_by_type as $type): ?>
            <div class="inqyra-stat-card">
                <div class="inqyra-stat-icon dashicons <?php echo esc_attr($type->content_type === 'website' ? 'dashicons-admin-site' : 'dashicons-media-document'); ?>"></div>
                <div class="inqyra-stat-content">
                    <div class="inqyra-stat-value"><?php echo esc_html($type->count); ?></div>
                    <div class="inqyra-stat-label">
                        <?php echo $type->content_type === 'website' ? esc_html__('Website Chunks', 'inqyra') : esc_html__('Document Chunks', 'inqyra'); ?>
                        <?php if ($type->pending > 0): ?>
                            <span class="inqyra-status-badge inqyra-status-warning"><?php echo esc_html($type->pending); ?> <?php esc_html_e('pending', 'inqyra'); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Indexing Controls (combined crawl + embeddings) -->
    <div class="inqyra-card" id="inqyra-indexing-card">
        <h2><?php esc_html_e('Content Indexing', 'inqyra'); ?></h2>

        <p class="description">
            <?php
            $idx_labels = class_exists('Inqyra_Indexing_Labels') ? Inqyra_Indexing_Labels::get('en') : [];
            echo esc_html($idx_labels['step_description'] ?? 'We\'ll read and process your website content so the chatbot can search through it intelligently.');
            ?>
        </p>

        <div id="inqyra-crawl-info">
            <?php if ($last_crawl): ?>
                <p>
                    <?php
                    printf(
                        /* translators: 1: Date, 2: Status */
                        esc_html__('Last indexed: %1$s - Status: %2$s', 'inqyra'),
                        esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_crawl->created_at))),
                        esc_html(ucfirst($last_crawl->status))
                    );
                    ?>
                </p>
                <?php if ($last_crawl->status === 'completed'): ?>
                    <p>
                        <?php
                        printf(
                            /* translators: 1: Processed posts, 2: Total posts, 3: Chunks created */
                            esc_html__('Processed %1$d of %2$d posts, created %3$d chunks.', 'inqyra'),
                            intval($last_crawl->processed_posts),
                            intval($last_crawl->total_posts),
                            intval($last_crawl->chunks_created)
                        );
                        ?>
                    </p>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Indexing status stats -->
        <div class="inqyra-embedding-stats" id="inqyra-index-stats">
            <div class="inqyra-embedding-stat">
                <span class="label"><?php esc_html_e('Total Chunks:', 'inqyra'); ?></span>
                <span id="total-chunks" class="value">-</span>
            </div>
            <div class="inqyra-embedding-stat">
                <span class="label"><?php esc_html_e('Searchable:', 'inqyra'); ?></span>
                <span id="with-embedding" class="value">-</span>
            </div>
            <div class="inqyra-embedding-stat">
                <span class="label"><?php esc_html_e('Pending:', 'inqyra'); ?></span>
                <span id="pending-embedding" class="value">-</span>
            </div>
            <div class="inqyra-embedding-stat">
                <span class="label"><?php esc_html_e('Progress:', 'inqyra'); ?></span>
                <span id="embedding-progress" class="value">-</span>
            </div>
        </div>

        <!-- Combined progress bar -->
        <div id="inqyra-index-progress" style="display: none;">
            <p id="inqyra-index-step-label" style="margin: 10px 0 5px; color: #646970; font-weight: 500;"></p>
            <div class="inqyra-crawl-progress-bar">
                <div class="inqyra-progress-fill" id="inqyra-index-progress-fill" style="width: 0%;"></div>
            </div>
        </div>

        <!-- Embedding-only progress bar (hidden by default) -->
        <div class="inqyra-embedding-progress-bar" style="display: none;">
            <div class="inqyra-progress-fill" style="width: 0%;"></div>
        </div>

        <p>
            <button type="button" class="button button-primary" id="inqyra-start-reindex" data-agent-id="<?php echo esc_attr($agent->id); ?>">
                <?php echo esc_html($idx_labels['reindex_button'] ?? 'Re-index'); ?>
            </button>
            <button type="button" class="button" id="inqyra-process-embeddings" data-agent-id="<?php echo esc_attr($agent->id); ?>" style="display: none;">
                <?php echo esc_html($idx_labels['process_pending'] ?? 'Make searchable'); ?>
            </button>
            <button type="button" class="button" id="inqyra-refresh-embedding-stats">
                <?php esc_html_e('Refresh Status', 'inqyra'); ?>
            </button>
            <span class="spinner" id="embedding-spinner"></span>
            <span id="inqyra-crawl-status"></span>
        </p>
        <p id="inqyra-embedding-message" class="description"></p>

        <p class="description" id="inqyra-pending-notice" style="display: none; margin-top: 5px; color: #b26200;">
            <?php echo esc_html($idx_labels['embedding_explain'] ?? 'Some items have been read but not yet made searchable. Click the button to finish this process.'); ?>
        </p>
    </div>

    <!-- Chunks List -->
    <div class="inqyra-card">
        <h2><?php esc_html_e('Knowledge Chunks', 'inqyra'); ?></h2>

        <?php if (empty($chunks)): ?>
            <p class="inqyra-empty-state"><?php esc_html_e('No knowledge chunks yet. Start a crawl to index your content.', 'inqyra'); ?></p>
        <?php else: ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width: 80px;"><?php esc_html_e('ID', 'inqyra'); ?></th>
                        <th><?php esc_html_e('Source', 'inqyra'); ?></th>
                        <th style="width: 100px;"><?php esc_html_e('Type', 'inqyra'); ?></th>
                        <th><?php esc_html_e('Content Preview', 'inqyra'); ?></th>
                        <th style="width: 100px;"><?php esc_html_e('Embedding', 'inqyra'); ?></th>
                        <th style="width: 150px;"><?php esc_html_e('Updated', 'inqyra'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($chunks as $chunk): ?>
                        <tr>
                            <td><?php echo esc_html($chunk->id); ?></td>
                            <td>
                                <?php if ($chunk->source_url): ?>
                                    <a href="<?php echo esc_url($chunk->source_url); ?>" target="_blank">
                                        <?php echo esc_html(wp_trim_words($chunk->source_url, 5)); ?>
                                    </a>
                                <?php else: ?>
                                    <?php echo esc_html($chunk->source_type); ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="inqyra-status-badge">
                                    <?php echo esc_html(ucfirst($chunk->content_type)); ?>
                                </span>
                            </td>
                            <td>
                                <span class="inqyra-content-preview">
                                    <?php echo esc_html(wp_trim_words($chunk->content, 20)); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($chunk->needs_embedding): ?>
                                    <span class="inqyra-status-badge inqyra-status-warning"><?php esc_html_e('Pending', 'inqyra'); ?></span>
                                <?php else: ?>
                                    <span class="inqyra-status-badge inqyra-status-success"><?php esc_html_e('Ready', 'inqyra'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($chunk->updated_at))); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($total_pages > 1): ?>
                <div class="tablenav bottom">
                    <div class="tablenav-pages">
                        <?php
                        echo wp_kses_post(paginate_links([
                            'base' => add_query_arg('paged', '%#%'),
                            'format' => '',
                            'prev_text' => '&laquo;',
                            'next_text' => '&raquo;',
                            'total' => $total_pages,
                            'current' => $current_page,
                        ]));
                        ?>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
