<?php

namespace Kanews\Kai\Chat;

use Kanews\Kai\Manager;
use Kanews\Kai\Support\Options;

class ChatController
{
    private $manager;

    public function __construct(Manager $manager)
    {
        $this->manager = $manager;
    }

    public function register(): void
    {
        add_action('wp_footer', [$this, 'maybeRenderChat']);
        add_action('wp_ajax_kanews_chat_message', [$this, 'handleChatMessage']);
        add_action('wp_ajax_nopriv_kanews_chat_message', [$this, 'handleChatMessage']);
    }

    public function maybeRenderChat(): void
    {
        if (!is_single()) {
            return;
        }

        $chatActive = (bool) Options::get('kai-chat-active', false);
        $postId     = get_queried_object_id();

        if (!$postId) {
            return;
        }

        $override = get_post_meta($postId, 'kai-chat-override', true);
        if ('on' === $override) {
            $chatActive = true;
        } elseif ('off' === $override) {
            $chatActive = false;
        }

        if (!$chatActive) {
            return;
        }

        $openAiKey = Options::getApiKey('openai');
        $geminiKey = Options::getApiKey('gemini');
        if (empty($openAiKey) && empty($geminiKey)) {
            echo $this->renderDisabledState();
            return;
        }

        $chatTitle        = Options::get('kai-chat-title', 'KAI ile Haber Hakkında Sohbet');
        $inputPlaceholder = Options::get('kai-chat-placeholder', 'Sorunuzu yazın...');

        $texts = [
            'welcome_free'     => (string) Options::get('kai-chat-text-welcome-free', 'Hoş geldiniz, günlük {free_limit} yazı için {free_limit}\'er soru sorabilirsiniz.'),
            'welcome_premium'  => (string) Options::get('kai-chat-text-welcome-premium', 'Hoş geldiniz, Premium üye olarak günlük {premium_limit} yazı için {premium_limit}\'er soru sorabilirsiniz.'),
            'remaining_free'   => (string) Options::get('kai-chat-text-remaining-free', 'Ücretsiz kullanıcı olarak {remaining} soru hakkınız kaldı.'),
            'remaining_premium'=> (string) Options::get('kai-chat-text-remaining-premium', 'Premium üye olarak {remaining} soru hakkınız kaldı.'),
            'upgrade_text'     => (string) Options::get('kai-chat-text-upgrade', 'Daha fazlası için <a href="{upgrade_url}">üyelik seçeneklerimizi</a> inceleyin.'),
        ];

        ?>
        <div class="kanews-chat">
            <div class="kanews-chat-button" role="tooltip" data-microtip-position="right" aria-label="<?php echo esc_attr($chatTitle); ?>">
                <?php $this->renderChatIcon(); ?>
            </div>
            <div class="kanews-chat-window">
                <div class="kanews-chat-header">
                    <div class="kanews-chat-title"><?php echo esc_html($chatTitle); ?></div>
                    <div class="close-chat"><i class="icon-close"></i></div>
                </div>
                <div class="kanews-chat-messages"></div>
                <div class="kanews-chat-remaining"></div>
                <div class="kanews-chat-input">
                    <input type="text" placeholder="<?php echo esc_attr($inputPlaceholder); ?>">
                    <button type="button">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="22" y1="2" x2="11" y2="13"></line>
                            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                        </svg>
                    </button>
                    <input type="hidden" name="kanews_chat_nonce" id="kanews_chat_nonce" value="<?php echo esc_attr(wp_create_nonce('kanews_chat_nonce')); ?>">
                </div>
            </div>
        </div>
        <script>
            window.kanews_chat_texts = <?php echo wp_json_encode($texts, JSON_UNESCAPED_UNICODE); ?>;
        </script>
        <?php
    }

    public function handleChatMessage(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'kanews_chat_nonce')) {
            wp_send_json_error(['message' => 'Güvenlik doğrulaması başarısız.']);
        }

        $articleId = isset($_POST['article_id']) ? intval($_POST['article_id']) : 0;
        $message   = sanitize_text_field($_POST['message'] ?? '');

        if (!$articleId || empty($message)) {
            wp_send_json_error(['message' => 'Geçersiz istek parametreleri.']);
        }

        $chatActive = (bool) Options::get('kai-chat-active', true);
        $override   = get_post_meta($articleId, 'kai-chat-override', true);
        if ('on' === $override) {
            $chatActive = true;
        } elseif ('off' === $override) {
            $chatActive = false;
        }

        if (!$chatActive) {
            wp_send_json_error(['message' => 'Sohbet sistemi bu makale için devre dışı.']);
        }

        $title   = (string) get_the_title($articleId);
        $content = get_post_field('post_content', $articleId);
        $snippet = is_string($content) ? wp_strip_all_tags($content) : '';
        $snippet = function_exists('mb_substr')
            ? (mb_substr($snippet, 0, 500) ?: substr($snippet, 0, 500))
            : substr($snippet, 0, 500);

        // Ensure at least one provider key exists before invoking AI.
        $openAiKey = Options::getApiKey('openai');
        $geminiKey = Options::getApiKey('gemini');
        if (empty($openAiKey) && empty($geminiKey)) {
            wp_send_json_error(['message' => __('Geçerli bir yapay zekâ anahtarı bulunamadı (OpenAI veya Gemini).', 'kanews')]);
        }

        try {
            $response = $this->manager->ai()->chat('chat-message', [
                'article_title' => $title,
                'snippet'       => $snippet,
                'user_message'  => $message,
            ]);

            wp_send_json_success([
                'message'        => $response['content'],
                'remaining'      => null,
                'status_message' => '',
            ]);
        } catch (\Throwable $th) {
            wp_send_json_error(['message' => 'API Hatası: ' . $th->getMessage()]);
        }
    }

    private function renderDisabledState(): string
    {
        ob_start();
        ?>
        <div class="kanews-chat">
            <div class="kanews-chat-button">
                <?php $this->renderChatIcon(); ?>
            </div>
            <div class="kanews-chat-window">
                <div class="kanews-chat-header">
                    <div class="kanews-chat-title"><?php echo esc_html(Options::get('kai-chat-title', 'KAI ile Haber Hakkında Sohbet')); ?></div>
                    <div class="close-chat"><i class="icon-close"></i></div>
                </div>
                <div class="kanews-chat-messages">
                    <div class="kanews-chat-message system-message">
                        Sohbet sistemi şu anda aktif değil. Lütfen daha sonra tekrar deneyin.
                    </div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    private function renderChatIcon(): void
    {
        ?>
        <svg width="40" height="40" viewBox="0 0 24 24" aria-label="Chat Bot Bubble Solid" xmlns="http://www.w3.org/2000/svg">
            <path fill="currentColor" d="M5 4h14a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3h-7l-4.5 3.6a.9.9 0 0 1-1.5-.7V16H5a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3Z"/>
            <g fill="#000">
                <circle cx="10" cy="9.5" r="1.1"/>
                <circle cx="14" cy="9.5" r="1.1"/>
                <rect x="9.2" y="11.3" width="5.6" height="1.6" rx="0.8"/>
            </g>
        </svg>
        <?php
    }
}

