<?php
/**
 * Page admin « Assistant IA ».
 */

defined('ABSPATH') || exit;

add_action('admin_menu', 'cvb_chatbot_admin_menu');
add_action('admin_head', 'cvb_chatbot_admin_styles');

function cvb_chatbot_admin_menu(): void {
    add_menu_page(
        'Assistant IA',
        'Assistant IA',
        'manage_options',
        'covalba-chatbot',
        'cvb_chatbot_render_admin_page',
        'dashicons-format-chat',
        58
    );
}

function cvb_chatbot_admin_styles(): void {
    if (($_GET['page'] ?? '') !== 'covalba-chatbot') {
        return;
    }
    ?>
    <style>
        .cvb-chatbot-md p { margin: 6px 0; }
        .cvb-chatbot-md p:first-child { margin-top: 0; }
        .cvb-chatbot-md p:last-child { margin-bottom: 0; }
        .cvb-chatbot-md ul { margin: 6px 0 6px 20px; list-style: disc; }
        .cvb-chatbot-md li { margin: 3px 0; }
        .cvb-chatbot-md code { background:#f0f0f1; padding:1px 4px; border-radius:3px; }
        .cvb-chatbot-md a { color:#1a6e6b; }
    </style>
    <?php
}

function cvb_chatbot_format_date($value): string {
    if (!$value || !is_string($value)) {
        return '—';
    }

    $timestamp = strtotime($value);
    if (!$timestamp) {
        return $value;
    }

    return date_i18n('d/m/Y H:i', $timestamp);
}

function cvb_chatbot_admin_url(array $args = []): string {
    return add_query_arg(array_merge(['page' => 'covalba-chatbot'], $args), admin_url('admin.php'));
}

function cvb_chatbot_notice(string $type, string $message): array {
    return ['type' => $type, 'message' => $message];
}

function cvb_chatbot_default_report_recipients(): string {
    return 'assous.tom@gmail.com';
}

function cvb_chatbot_read_textarea(string $key): string {
    if (!isset($_POST[$key]) || !is_string($_POST[$key])) {
        return '';
    }

    return trim(wp_check_invalid_utf8((string) wp_unslash($_POST[$key])));
}

function cvb_chatbot_normalize_report_recipients(string $raw, array &$invalid = []): string {
    $raw = trim($raw);
    if ($raw === '') {
        $raw = cvb_chatbot_default_report_recipients();
    }

    $raw = (string) preg_replace('/\s*@\s*/', '@', $raw);
    $parts = preg_split('/[\s,;]+/', $raw) ?: [];
    $emails = [];

    foreach ($parts as $part) {
        $email = strtolower(trim($part));
        if ($email === '') {
            continue;
        }

        $sanitized = sanitize_email($email);
        if (!$sanitized || !is_email($sanitized)) {
            $invalid[] = $email;
            continue;
        }

        $emails[$sanitized] = true;
    }

    if (!$emails && !$invalid) {
        $emails[cvb_chatbot_default_report_recipients()] = true;
    }

    return implode(', ', array_keys($emails));
}

function cvb_chatbot_markdown_inline(string $text): string {
    $html = esc_html($text);

    $html = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/', static function (array $matches): string {
        $label = $matches[1];
        $url = esc_url(html_entity_decode($matches[2], ENT_QUOTES));
        if ($url === '') {
            return $label;
        }

        return sprintf(
            '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
            esc_url($url),
            $label
        );
    }, $html) ?? $html;

    $html = preg_replace('/`([^`]+)`/', '<code>$1</code>', $html) ?? $html;
    $html = preg_replace('/\*\*([^*]+)\*\*/', '<strong>$1</strong>', $html) ?? $html;

    return $html;
}

function cvb_chatbot_render_markdown(string $markdown): string {
    $lines = preg_split('/\R/', wp_check_invalid_utf8($markdown)) ?: [];
    $html = '';
    $paragraph = [];
    $list_items = [];

    $flush_paragraph = static function () use (&$html, &$paragraph): void {
        if (!$paragraph) {
            return;
        }
        $html .= '<p>' . implode('<br>', array_map('cvb_chatbot_markdown_inline', $paragraph)) . '</p>';
        $paragraph = [];
    };

    $flush_list = static function () use (&$html, &$list_items): void {
        if (!$list_items) {
            return;
        }
        $html .= '<ul>';
        foreach ($list_items as $item) {
            $html .= '<li>' . cvb_chatbot_markdown_inline($item) . '</li>';
        }
        $html .= '</ul>';
        $list_items = [];
    };

    foreach ($lines as $line) {
        $trimmed = trim($line);
        if ($trimmed === '') {
            $flush_paragraph();
            $flush_list();
            continue;
        }

        if (preg_match('/^[-*]\s+(.+)$/', $trimmed, $matches)) {
            $flush_paragraph();
            $list_items[] = $matches[1];
            continue;
        }

        $flush_list();
        $paragraph[] = $trimmed;
    }

    $flush_paragraph();
    $flush_list();

    return wp_kses($html, [
        'p' => [],
        'br' => [],
        'ul' => [],
        'li' => [],
        'strong' => [],
        'code' => [],
        'a' => [
            'href' => [],
            'target' => [],
            'rel' => [],
        ],
    ]);
}

function cvb_chatbot_handle_save(): array {
    if (($_POST['cvb_chatbot_action'] ?? '') !== 'save_settings') {
        return [];
    }

    check_admin_referer('cvb_chatbot_save_settings');

    if (!current_user_can('manage_options')) {
        return [cvb_chatbot_notice('error', 'Permission refusée.')];
    }

    $enabled = isset($_POST['enabled']);
    $app_url = isset($_POST['app_url']) && is_string($_POST['app_url'])
        ? esc_url_raw(wp_unslash($_POST['app_url']))
        : '';
    $invalid_emails = [];
    $report_recipients = cvb_chatbot_normalize_report_recipients(
        isset($_POST['report_recipients']) && is_string($_POST['report_recipients'])
            ? (string) wp_unslash($_POST['report_recipients'])
            : '',
        $invalid_emails
    );

    if ($invalid_emails) {
        return [
            cvb_chatbot_notice('error', 'Email invalide dans la liste du rapport : ' . implode(', ', $invalid_emails)),
        ];
    }

    cvb_chatbot_update_settings($enabled, $app_url);
    cvb_chatbot_revalidate_front();

    $payload = [
        'enabled' => $enabled,
        'reportRecipients' => $report_recipients,
    ];
    $prompt = cvb_chatbot_read_textarea('system_prompt_rules');
    if ($prompt !== '') {
        $payload['systemPromptRules'] = $prompt;
    }
    $knowledge = cvb_chatbot_read_textarea('knowledge_markdown');
    if ($knowledge !== '') {
        $payload['knowledgeMarkdown'] = $knowledge;
    }

    $remote = cvb_chatbot_request('PATCH', '/api/wp-chatbot/settings', $payload);
    if (is_wp_error($remote)) {
        return [
            cvb_chatbot_notice('warning', 'Réglages locaux sauvegardés, mais la synchronisation avec le service chatbot a échoué : ' . $remote->get_error_message()),
        ];
    }

    return [cvb_chatbot_notice('success', 'Réglages chatbot sauvegardés.')];
}

function cvb_chatbot_handle_summary(?array &$summary, int &$summary_days): array {
    if (($_POST['cvb_chatbot_action'] ?? '') !== 'generate_summary') {
        return [];
    }

    check_admin_referer('cvb_chatbot_generate_summary');

    if (!current_user_can('manage_options')) {
        return [cvb_chatbot_notice('error', 'Permission refusée.')];
    }

    $requested_days = (int) ($_POST['summary_days'] ?? 30);
    $summary_days = in_array($requested_days, [7, 30, 90], true) ? $requested_days : 30;
    $remote = cvb_chatbot_request('POST', '/api/wp-chatbot/summary', [
        'days' => $summary_days,
    ], 60);

    if (is_wp_error($remote)) {
        return [
            cvb_chatbot_notice('warning', 'Le récap IA n’a pas pu être généré : ' . $remote->get_error_message()),
        ];
    }

    $summary = is_array($remote) ? $remote : null;
    return [cvb_chatbot_notice('success', 'Récap IA généré.')];
}

function cvb_chatbot_render_notices(array $notices): void {
    foreach ($notices as $notice) {
        $type = in_array($notice['type'] ?? '', ['success', 'warning', 'error', 'info'], true)
            ? $notice['type']
            : 'info';
        printf(
            '<div class="notice notice-%s"><p>%s</p></div>',
            esc_attr($type),
            esc_html($notice['message'] ?? '')
        );
    }
}

function cvb_chatbot_render_dashboard(array $dashboard): void {
    $kpis = isset($dashboard['kpis']) && is_array($dashboard['kpis']) ? $dashboard['kpis'] : [];
    $top_pages = isset($kpis['topPages']) && is_array($kpis['topPages']) ? $kpis['topPages'] : [];
    $pct = isset($kpis['pctHandled']) ? (float) $kpis['pctHandled'] : 0.0;
    $cards = [
        'Discussions' => (string) ($kpis['convs'] ?? 0),
        'Messages' => (string) ($kpis['msgs'] ?? 0),
        'Questions sans réponse' => (string) ($kpis['unanswered'] ?? 0),
        'Taux traité' => (string) round($pct * 100) . ' %',
    ];
    ?>
    <div class="postbox" style="padding:16px;max-width:1100px;">
        <h2 style="margin-top:0;">Tableau de bord</h2>
        <div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px;">
            <?php foreach ($cards as $label => $value) : ?>
                <div style="border:1px solid #dcdcde;background:#fff;padding:12px;">
                    <div style="font-size:24px;font-weight:700;line-height:1.1;"><?php echo esc_html($value); ?></div>
                    <div class="description"><?php echo esc_html($label); ?></div>
                </div>
            <?php endforeach; ?>
        </div>

        <h3>Pages les plus recommandées</h3>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th>Page</th>
                    <th>URL</th>
                    <th>Recommandations</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$top_pages) : ?>
                    <tr><td colspan="3">Aucune donnée pour l’instant.</td></tr>
                <?php endif; ?>
                <?php foreach (array_slice($top_pages, 0, 8) as $page) : ?>
                    <tr>
                        <td><?php echo esc_html((string) ($page['label'] ?? '—')); ?></td>
                        <td><span class="description"><?php echo esc_html((string) ($page['url'] ?? '—')); ?></span></td>
                        <td><?php echo esc_html((string) ($page['n'] ?? 0)); ?>×</td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
}

function cvb_chatbot_render_summary_form(?array $summary, int $summary_days): void {
    ?>
    <div class="postbox" style="padding:16px;max-width:1100px;">
        <h2 style="margin-top:0;">Récap IA</h2>
        <form method="post" action="<?php echo esc_url(cvb_chatbot_admin_url()); ?>" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
            <?php wp_nonce_field('cvb_chatbot_generate_summary'); ?>
            <input type="hidden" name="cvb_chatbot_action" value="generate_summary" />
            <label for="cvb-chatbot-summary-days">Période</label>
            <select id="cvb-chatbot-summary-days" name="summary_days">
                <?php foreach ([7, 30, 90] as $days) : ?>
                    <option value="<?php echo esc_attr((string) $days); ?>" <?php selected($summary_days, $days); ?>>
                        <?php echo esc_html((string) $days); ?> jours
                    </option>
                <?php endforeach; ?>
            </select>
            <?php submit_button('Générer un récap IA', 'secondary', 'submit', false); ?>
        </form>

        <?php if ($summary && isset($summary['summary'])) : ?>
            <?php $stats = isset($summary['stats']) && is_array($summary['stats']) ? $summary['stats'] : []; ?>
            <p class="description">
                <?php echo esc_html((string) ($stats['nbConv'] ?? 0)); ?> discussions ·
                <?php echo esc_html((string) ($stats['nbMsg'] ?? 0)); ?> messages ·
                <?php echo esc_html((string) ($stats['days'] ?? $summary_days)); ?> jours
            </p>
            <div class="cvb-chatbot-md" style="background:#fff;border:1px solid #dcdcde;padding:12px;">
                <?php echo cvb_chatbot_render_markdown((string) $summary['summary']); ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}

function cvb_chatbot_render_admin_page(): void {
    $summary = null;
    $summary_days = 30;
    $notices = array_merge(
        cvb_chatbot_handle_save(),
        cvb_chatbot_handle_summary($summary, $summary_days)
    );
    $local_settings = cvb_chatbot_get_settings();

    $remote_settings = cvb_chatbot_request('GET', '/api/wp-chatbot/settings');
    if (is_wp_error($remote_settings)) {
        $notices[] = cvb_chatbot_notice('warning', 'Service chatbot indisponible : ' . $remote_settings->get_error_message());
        $remote_settings = [];
    }

    $dashboard = cvb_chatbot_request('GET', '/api/wp-chatbot/dashboard');
    if (is_wp_error($dashboard)) {
        $notices[] = cvb_chatbot_notice('warning', 'Tableau de bord indisponible : ' . $dashboard->get_error_message());
        $dashboard = [];
    }

    $page = max(0, (int) ($_GET['chatbot_page'] ?? 0));
    $conversation_id = isset($_GET['conversation_id']) && is_string($_GET['conversation_id'])
        ? sanitize_text_field(wp_unslash($_GET['conversation_id']))
        : '';

    $thread = null;
    if ($conversation_id !== '') {
        $thread = cvb_chatbot_request('GET', '/api/wp-chatbot/conversations/' . rawurlencode($conversation_id));
        if (is_wp_error($thread)) {
            $notices[] = cvb_chatbot_notice('warning', 'Conversation introuvable ou inaccessible : ' . $thread->get_error_message());
            $thread = null;
        }
    }

    $conversations = cvb_chatbot_request('GET', '/api/wp-chatbot/conversations?page=' . $page . '&size=20');
    if (is_wp_error($conversations)) {
        $notices[] = cvb_chatbot_notice('warning', 'Historique indisponible : ' . $conversations->get_error_message());
        $conversations = ['items' => [], 'hasMore' => false];
    }

    $prompt = is_array($remote_settings) && isset($remote_settings['systemPromptRules'])
        ? (string) $remote_settings['systemPromptRules']
        : '';
    $knowledge = is_array($remote_settings) && isset($remote_settings['knowledgeMarkdown'])
        ? (string) $remote_settings['knowledgeMarkdown']
        : (is_array($remote_settings) && isset($remote_settings['defaultKnowledgeMarkdown'])
            ? (string) $remote_settings['defaultKnowledgeMarkdown']
            : '');
    $report_recipients = is_array($remote_settings) && isset($remote_settings['reportRecipients'])
        ? (string) $remote_settings['reportRecipients']
        : (is_array($remote_settings) && isset($remote_settings['defaultReportRecipients'])
            ? (string) $remote_settings['defaultReportRecipients']
            : cvb_chatbot_default_report_recipients());
    $remote_enabled = is_array($remote_settings) && array_key_exists('enabled', $remote_settings)
        ? (bool) $remote_settings['enabled']
        : (bool) $local_settings['enabled'];
    ?>
    <div class="wrap">
        <h1>Assistant IA Covalba</h1>
        <?php cvb_chatbot_render_notices($notices); ?>

        <?php cvb_chatbot_render_dashboard(is_array($dashboard) ? $dashboard : []); ?>
        <?php cvb_chatbot_render_summary_form($summary, $summary_days); ?>

        <div class="postbox" style="padding:16px;max-width:1100px;">
            <h2 style="margin-top:0;">Réglages</h2>
            <form method="post" action="<?php echo esc_url(cvb_chatbot_admin_url()); ?>">
                <?php wp_nonce_field('cvb_chatbot_save_settings'); ?>
                <input type="hidden" name="cvb_chatbot_action" value="save_settings" />

                <table class="form-table" role="presentation">
                    <tbody>
                        <tr>
                            <th scope="row">Activation</th>
                            <td>
                                <label>
                                    <input type="checkbox" name="enabled" value="1" <?php checked($remote_enabled && (bool) $local_settings['enabled']); ?> />
                                    Activer le bot sur le site et côté API chatbot
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cvb-chatbot-app-url">URL du service</label></th>
                            <td>
                                <input
                                    id="cvb-chatbot-app-url"
                                    name="app_url"
                                    type="url"
                                    class="regular-text"
                                    value="<?php echo esc_attr($local_settings['app_url']); ?>"
                                    placeholder="https://covalba-chatbot.vercel.app"
                                />
                                <p class="description">Origine de l'app chatbot, sans slash final. Le widget chargera <code>/widget.js</code>.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cvb-chatbot-system-prompt">System prompt</label></th>
                            <td>
                                <textarea
                                    id="cvb-chatbot-system-prompt"
                                    name="system_prompt_rules"
                                    rows="18"
                                    class="large-text code"
                                ><?php echo esc_textarea($prompt); ?></textarea>
                                <p class="description">Règles système modifiables. Elles sont combinées à la base de connaissances ci-dessous.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cvb-chatbot-knowledge">Knowledge.md</label></th>
                            <td>
                                <textarea
                                    id="cvb-chatbot-knowledge"
                                    name="knowledge_markdown"
                                    rows="22"
                                    class="large-text code"
                                ><?php echo esc_textarea($knowledge); ?></textarea>
                                <p class="description">Base de connaissances utilisée par le bot. Le fichier versionné reste le fallback si aucun override n’est enregistré.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cvb-chatbot-report-recipients">Emails du rapport mensuel</label></th>
                            <td>
                                <textarea
                                    id="cvb-chatbot-report-recipients"
                                    name="report_recipients"
                                    rows="3"
                                    class="large-text code"
                                ><?php echo esc_textarea($report_recipients); ?></textarea>
                                <p class="description">Liste séparée par virgules ou retours ligne. Par défaut : <code>assous.tom@gmail.com</code>.</p>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <?php submit_button('Enregistrer'); ?>
            </form>
        </div>

        <?php if (is_array($remote_settings) && array_key_exists('dbConfigured', $remote_settings) && !$remote_settings['dbConfigured']) : ?>
            <div class="notice notice-warning inline">
                <p>La base du service chatbot n'est pas configurée : le prompt et l'historique ne peuvent pas être persistés.</p>
            </div>
        <?php endif; ?>

        <?php cvb_chatbot_render_history($conversations, $thread, $conversation_id, $page); ?>
    </div>
    <?php
}

function cvb_chatbot_render_history(array $conversations, ?array $thread, string $conversation_id, int $page): void {
    ?>
    <h2>Historique des conversations</h2>
    <?php if ($thread) : ?>
        <?php cvb_chatbot_render_thread($thread); ?>
        <p><a href="<?php echo esc_url(cvb_chatbot_admin_url(['chatbot_page' => $page])); ?>">← Retour à la liste</a></p>
    <?php else : ?>
        <?php cvb_chatbot_render_conversation_table($conversations, $page); ?>
    <?php endif; ?>
    <?php
}

function cvb_chatbot_render_conversation_table(array $conversations, int $page): void {
    $items = isset($conversations['items']) && is_array($conversations['items']) ? $conversations['items'] : [];
    $has_more = !empty($conversations['hasMore']);
    ?>
    <table class="widefat striped">
        <thead>
            <tr>
                <th>Aperçu</th>
                <th>Dernier message</th>
                <th>Messages</th>
                <th>Modèle</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!$items) : ?>
                <tr><td colspan="4">Aucune conversation.</td></tr>
            <?php endif; ?>
            <?php foreach ($items as $item) : ?>
                <?php
                $id = isset($item['id']) ? (string) $item['id'] : '';
                $preview = isset($item['preview']) ? (string) $item['preview'] : '(sans message)';
                ?>
                <tr>
                    <td>
                        <a href="<?php echo esc_url(cvb_chatbot_admin_url(['conversation_id' => $id, 'chatbot_page' => $page])); ?>">
                            <?php echo esc_html(wp_trim_words($preview, 18)); ?>
                        </a>
                    </td>
                    <td><?php echo esc_html(cvb_chatbot_format_date($item['lastMessageAt'] ?? null)); ?></td>
                    <td><?php echo esc_html((string) ($item['messageCount'] ?? '0')); ?></td>
                    <td><?php echo esc_html((string) ($item['model'] ?? '—')); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <p style="display:flex;gap:12px;">
        <?php if ($page > 0) : ?>
            <a class="button" href="<?php echo esc_url(cvb_chatbot_admin_url(['chatbot_page' => $page - 1])); ?>">Précédent</a>
        <?php endif; ?>
        <?php if ($has_more) : ?>
            <a class="button" href="<?php echo esc_url(cvb_chatbot_admin_url(['chatbot_page' => $page + 1])); ?>">Suivant</a>
        <?php endif; ?>
    </p>
    <?php
}

function cvb_chatbot_render_thread(array $thread): void {
    $conv = isset($thread['conv']) && is_array($thread['conv']) ? $thread['conv'] : [];
    $messages = isset($thread['msgs']) && is_array($thread['msgs']) ? $thread['msgs'] : [];
    $events = isset($thread['evts']) && is_array($thread['evts']) ? $thread['evts'] : [];
    ?>
    <div class="postbox" style="padding:16px;max-width:1100px;">
        <h3 style="margin-top:0;">Conversation <?php echo esc_html(substr((string) ($conv['id'] ?? ''), 0, 8)); ?>…</h3>
        <p class="description">
            <?php echo esc_html(cvb_chatbot_format_date($conv['createdAt'] ?? null)); ?>
            · <?php echo esc_html((string) ($conv['messageCount'] ?? '0')); ?> messages
            · <?php echo esc_html((string) ($conv['model'] ?? '—')); ?>
        </p>

        <?php foreach ($messages as $message) : ?>
            <?php $role = (string) ($message['role'] ?? ''); ?>
            <div style="margin:12px 0;padding:10px 12px;border-left:4px solid <?php echo $role === 'user' ? '#1a6e6b' : '#0e1c2e'; ?>;background:#fff;">
                <strong><?php echo esc_html($role === 'user' ? 'Visiteur' : 'Assistant'); ?></strong>
                <div class="cvb-chatbot-md" style="margin-top:6px;">
                    <?php if ($role === 'assistant') : ?>
                        <?php echo cvb_chatbot_render_markdown((string) ($message['content'] ?? '')); ?>
                    <?php else : ?>
                        <?php echo nl2br(esc_html((string) ($message['content'] ?? ''))); ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>

        <h4>Événements</h4>
        <?php if (!$events) : ?>
            <p>Aucun événement.</p>
        <?php endif; ?>
        <?php foreach ($events as $event) : ?>
            <p>
                <code><?php echo esc_html((string) ($event['type'] ?? '')); ?></code>
                <?php if (($event['type'] ?? '') === 'page_suggested') : ?>
                    <?php echo esc_html((string) ($event['label'] ?? '')); ?>
                    <span class="description"><?php echo esc_html((string) ($event['url'] ?? '')); ?></span>
                <?php elseif (($event['type'] ?? '') === 'unanswered') : ?>
                    <?php echo esc_html((string) ($event['question'] ?? '')); ?>
                <?php else : ?>
                    <span class="description"><?php echo esc_html(wp_json_encode($event['data'] ?? [])); ?></span>
                <?php endif; ?>
                <span class="description"> · <?php echo esc_html(cvb_chatbot_format_date($event['createdAt'] ?? null)); ?></span>
            </p>
        <?php endforeach; ?>
    </div>
    <?php
}
