<?php
declare(strict_types=1);

namespace KbMarkdownImporter\Admin;

use KbMarkdownImporter\GitLab\GitLabClient;
use KbMarkdownImporter\Import\ImportLogger;
use KbMarkdownImporter\Import\ImportManager;
use KbMarkdownImporter\Plugin;

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

        self::handleActions();
        $projects = self::loadProjects();
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Knowledgebase Synchronization', 'kb-markdown-importer'); ?></h1>
            <form method="post" class="kb-sync-actions">
                <?php wp_nonce_field('kb_markdown_sync'); ?>
                <?php submit_button(__('Sync All', 'kb-markdown-importer'), 'primary', 'kb_markdown_sync_all', false); ?>
                <?php submit_button(__('Dry Run', 'kb-markdown-importer'), 'secondary', 'kb_markdown_dry_run', false); ?>
            </form>

            <h2><?php esc_html_e('Projects', 'kb-markdown-importer'); ?></h2>
            <?php if (is_wp_error($projects)) : ?>
                <div class="notice notice-error"><p><?php echo esc_html($projects->get_error_message()); ?></p></div>
            <?php elseif (! $projects) : ?>
                <p><?php esc_html_e('No projects loaded. Check GitLab settings first.', 'kb-markdown-importer'); ?></p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead><tr><th>Name</th><th>Path</th><th>Action</th></tr></thead>
                    <tbody>
                    <?php foreach ($projects as $project) : ?>
                        <tr>
                            <td><?php echo esc_html((string) ($project['name'] ?? '')); ?></td>
                            <td><code><?php echo esc_html((string) ($project['path_with_namespace'] ?? $project['path'] ?? '')); ?></code></td>
                            <td>
                                <form method="post">
                                    <?php wp_nonce_field('kb_markdown_sync_project'); ?>
                                    <input type="hidden" name="project_id" value="<?php echo esc_attr((string) ($project['id'] ?? '')); ?>">
                                    <?php submit_button(__('Sync Project', 'kb-markdown-importer'), 'secondary small', 'kb_markdown_sync_project', false); ?>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

            <h2><?php esc_html_e('Import Logs', 'kb-markdown-importer'); ?></h2>
            <?php StatusPage::renderLogTable(ImportLogger::recent(100)); ?>
        </div>
        <?php
    }

    private static function handleActions(): void
    {
        if (isset($_POST['kb_markdown_sync_all']) && check_admin_referer('kb_markdown_sync')) {
            (new ImportManager())->syncAll(false);
            echo '<div class="notice notice-success"><p>' . esc_html__('Synchronization finished.', 'kb-markdown-importer') . '</p></div>';
        }

        if (isset($_POST['kb_markdown_dry_run']) && check_admin_referer('kb_markdown_sync')) {
            (new ImportManager())->syncAll(true);
            echo '<div class="notice notice-info"><p>' . esc_html__('Dry run finished.', 'kb-markdown-importer') . '</p></div>';
        }

        if (isset($_POST['kb_markdown_sync_project']) && check_admin_referer('kb_markdown_sync_project')) {
            $projectId = sanitize_text_field(wp_unslash((string) ($_POST['project_id'] ?? '')));
            (new ImportManager())->syncProject($projectId, false);
            echo '<div class="notice notice-success"><p>' . esc_html__('Project synchronization finished.', 'kb-markdown-importer') . '</p></div>';
        }
    }

    private static function loadProjects(): array|\WP_Error
    {
        $settings = Plugin::settings();

        if (! $settings['gitlab_base_url'] || ! $settings['gitlab_token'] || ! $settings['gitlab_group']) {
            return [];
        }

        $client = new GitLabClient($settings);
        $group = $client->getGroup($settings['gitlab_group']);

        if (is_wp_error($group)) {
            return $group;
        }

        return $client->getProjects((string) ($group['id'] ?? $settings['gitlab_group']));
    }
}
