<?php
declare(strict_types=1);

namespace KbMarkdownImporter\Admin;

use KbMarkdownImporter\Import\ImportLogger;
use KbMarkdownImporter\Plugin;

final class StatusPage
{
    public static function render(): void
    {
        if (! current_user_can('manage_kb_docs')) {
            wp_die(esc_html__('Insufficient permissions.', 'kb-markdown-importer'));
        }

        $settings = Plugin::settings();
        $counts = self::counts();
        $logs = ImportLogger::recent(20);
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Knowledgebase Overview', 'kb-markdown-importer'); ?></h1>
            <div class="kb-admin-grid">
                <div class="kb-admin-card"><strong>GitLab</strong><span><?php echo esc_html($settings['gitlab_base_url'] ?: __('Not configured', 'kb-markdown-importer')); ?></span></div>
                <div class="kb-admin-card"><strong>Products</strong><span><?php echo esc_html((string) $counts['products']); ?></span></div>
                <div class="kb-admin-card"><strong>Versions</strong><span><?php echo esc_html((string) $counts['versions']); ?></span></div>
                <div class="kb-admin-card"><strong>Pages</strong><span><?php echo esc_html((string) $counts['pages']); ?></span></div>
                <div class="kb-admin-card"><strong>Last sync</strong><span><?php echo esc_html((string) get_option('kb_markdown_importer_last_sync', __('Never', 'kb-markdown-importer'))); ?></span></div>
                <div class="kb-admin-card"><strong>Format</strong><span>Markdown</span></div>
            </div>
            <h2><?php esc_html_e('Recent Import Logs', 'kb-markdown-importer'); ?></h2>
            <?php self::renderLogTable($logs); ?>
        </div>
        <?php
    }

    public static function restStatus(): \WP_REST_Response
    {
        return new \WP_REST_Response([
            'settings_complete' => (bool) (Plugin::settings()['gitlab_base_url'] && Plugin::settings()['gitlab_token']),
            'counts' => self::counts(),
            'last_sync' => get_option('kb_markdown_importer_last_sync', ''),
            'last_error' => get_option('kb_markdown_importer_last_error', ''),
        ]);
    }

    public static function renderLogTable(array $logs): void
    {
        if (! $logs) {
            echo '<p>' . esc_html__('No logs yet.', 'kb-markdown-importer') . '</p>';
            return;
        }

        echo '<table class="widefat striped"><thead><tr><th>Time</th><th>Level</th><th>Message</th></tr></thead><tbody>';
        foreach ($logs as $entry) {
            printf(
                '<tr><td>%s</td><td><strong>%s</strong></td><td>%s</td></tr>',
                esc_html((string) ($entry['time'] ?? '')),
                esc_html((string) ($entry['level'] ?? 'INFO')),
                esc_html((string) ($entry['message'] ?? ''))
            );
        }
        echo '</tbody></table>';
    }

    private static function counts(): array
    {
        $pages = wp_count_posts('kb_doc_page');
        $products = wp_count_terms(['taxonomy' => 'kb_product', 'hide_empty' => false]);
        $versions = wp_count_terms(['taxonomy' => 'kb_version', 'hide_empty' => false]);

        return [
            'products' => is_wp_error($products) ? 0 : (int) $products,
            'versions' => is_wp_error($versions) ? 0 : (int) $versions,
            'pages' => (int) ($pages->publish ?? 0),
        ];
    }
}
