<?php

namespace Kanews\Kai\Admin;

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

class AdminPageRenderer
{
    private $manager;

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

    public function render(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Ensure default option values exist in dedicated KAI storage
        $this->ensureDefaultOptions();

        // Section IDs
        $kaiSettingsId = 'kai-settings';
        $kaiFeedsId = 'kai-feeds';
        $kaiAudioId = 'kai-audio';

        $state = $this->manager->feeds()->getState();
        $feeds = $state['feeds'];
        $notice = get_transient('kanews_kai_notice');
        if ($notice) {
            delete_transient('kanews_kai_notice');
        }

        $defaultAuthor = get_current_user_id();
        $defaultStatus = 'publish';

        // Load current KAI-related options from dedicated storage
        $opts = get_option('kanews_kai_options', []);
        $openaiApi = isset($opts['openai-api']) ? (string) $opts['openai-api'] : '';
        $pexelsApi = isset($opts['pexels-api']) ? (string) $opts['pexels-api'] : '';
        $chatActive = !empty($opts['kai-chat-active']);
        $chatTitle = isset($opts['kai-chat-title']) ? (string) $opts['kai-chat-title'] : 'KAI ile Haber Hakkında Sohbet';
        $chatPlaceholder = isset($opts['kai-chat-placeholder']) ? (string) $opts['kai-chat-placeholder'] : 'Sorunuzu yazın...';
        $chatFreeLimit = isset($opts['kai-chat-free-limit']) ? intval($opts['kai-chat-free-limit']) : 5;
        $chatPremiumLimit = isset($opts['kai-chat-premium-limit']) ? intval($opts['kai-chat-premium-limit']) : 20;
        $chatTextWelcomeFree = isset($opts['kai-chat-text-welcome-free']) ? (string) $opts['kai-chat-text-welcome-free'] : 'Hoş geldiniz, günlük {free_limit} yazı için {free_limit}\'er soru sorabilirsiniz.';
        $chatTextWelcomePremium = isset($opts['kai-chat-text-welcome-premium']) ? (string) $opts['kai-chat-text-welcome-premium'] : 'Hoş geldiniz, Premium üye olarak günlük {premium_limit} yazı için {premium_limit}\'er soru sorabilirsiniz.';
        $chatTextRemainingFree = isset($opts['kai-chat-text-remaining-free']) ? (string) $opts['kai-chat-text-remaining-free'] : 'Ücretsiz kullanıcı olarak {remaining} soru hakkınız kaldı.';
        $chatTextRemainingPremium = isset($opts['kai-chat-text-remaining-premium']) ? (string) $opts['kai-chat-text-remaining-premium'] : 'Premium üye olarak {remaining} soru hakkınız kaldı.';
        $chatTextUpgrade = isset($opts['kai-chat-text-upgrade']) ? (string) $opts['kai-chat-text-upgrade'] : 'Daha fazlası için <a href="{upgrade_url}">üyelik seçeneklerimizi</a> inceleyin.';
        $audioEnabled = !empty($opts['kai-audio-enabled']);
        $audioPaused = !empty($opts['kai-audio-paused']);
        $audioVoice = isset($opts['kai-audio-voice']) ? (string) $opts['kai-audio-voice'] : 'alloy';
        $audioDailyCount = isset($opts['kai-audio-daily-count']) ? intval($opts['kai-audio-daily-count']) : 3;
        $audioHeroEyebrow = isset($opts['kai-audio-hero-eyebrow']) ? (string) $opts['kai-audio-hero-eyebrow'] : get_bloginfo('name');
        $audioHeroTitle = isset($opts['kai-audio-hero-title']) ? (string) $opts['kai-audio-hero-title'] : __('Haber Bülteni', 'kanews');
        $audioHeroDesc = isset($opts['kai-audio-hero-description']) ? (string) $opts['kai-audio-hero-description'] : __('Günün kritik başlıklarını KAI üç farklı zaman diliminde ses dosyasına dönüştürür.', 'kanews');
        $availableVoices = [
            'alloy' => __('Alloy · Dengeli ton', 'kanews'),
            'verse' => __('Verse · Doğal konuşma', 'kanews'),
            'coral' => __('Coral · Sıcak ve yumuşak', 'kanews'),
            'sol' => __('Sol · Enerjik anlatım', 'kanews'),
        ];

        $currentInterval = isset($state['settings']['interval']) ? $state['settings']['interval'] : 'hourly';

        // Render the admin page
        $feedImageSources = $this->manager->feeds()->availableImageSources();
        $defaultFeedImageSource = $this->manager->feeds()->defaultImageSource();
        $feedAiModels = $this->manager->feeds()->availableAiModels();
        $defaultFeedAiModel = $this->manager->feeds()->defaultAiModel();

        $editingFeedId = isset($_GET['edit_feed']) ? sanitize_text_field(wp_unslash($_GET['edit_feed'])) : '';
        $editingFeed = null;
        if ($editingFeedId) {
            foreach ($feeds as $feed) {
                if (($feed['id'] ?? '') === $editingFeedId) {
                    $editingFeed = $feed;
                    break;
                }
            }
        }

        $this->renderPageContent(
            $kaiSettingsId,
            $kaiFeedsId,
            $kaiAudioId,
            $state,
            $feeds,
            $notice,
            $defaultAuthor,
            $defaultStatus,
            $opts,
            $openaiApi,
            $pexelsApi,
            $chatActive,
            $chatTitle,
            $chatPlaceholder,
            $chatFreeLimit,
            $chatPremiumLimit,
            $chatTextWelcomeFree,
            $chatTextWelcomePremium,
            $chatTextRemainingFree,
            $chatTextRemainingPremium,
            $chatTextUpgrade,
            $audioEnabled,
            $audioPaused,
            $audioVoice,
            $audioDailyCount,
            $audioHeroEyebrow,
            $audioHeroTitle,
            $audioHeroDesc,
            $availableVoices,
            $currentInterval,
            $feedImageSources,
            $defaultFeedImageSource,
            $feedAiModels,
            $defaultFeedAiModel,
            $editingFeed
        );
    }

    private function renderPageContent(...$args): void
    {
        // Extract all variables
        [
            $kaiSettingsId,
            $kaiFeedsId,
            $kaiAudioId,
            $state,
            $feeds,
            $notice,
            $defaultAuthor,
            $defaultStatus,
            $opts,
            $openaiApi,
            $pexelsApi,
            $chatActive,
            $chatTitle,
            $chatPlaceholder,
            $chatFreeLimit,
            $chatPremiumLimit,
            $chatTextWelcomeFree,
            $chatTextWelcomePremium,
            $chatTextRemainingFree,
            $chatTextRemainingPremium,
            $chatTextUpgrade,
            $audioEnabled,
            $audioPaused,
            $audioVoice,
            $audioDailyCount,
            $audioHeroEyebrow,
            $audioHeroTitle,
            $audioHeroDesc,
            $availableVoices,
            $currentInterval,
            $feedImageSources,
            $defaultFeedImageSource,
            $feedAiModels,
            $defaultFeedAiModel,
            $editingFeed
        ] = $args;

        $geminiApi = Options::getApiKey( 'gemini' );
        $hasOpenAi  = ! empty( $openaiApi );
        $hasGemini  = ! empty( $geminiApi );
        $apiStatusLabel = ( $hasOpenAi && $hasGemini )
            ? __( 'OpenAI · Gemini', 'kanews' )
            : ( $hasOpenAi ? __( 'OpenAI aktif', 'kanews' ) : ( $hasGemini ? __( 'Gemini aktif', 'kanews' ) : __( 'API hatası', 'kanews' ) ) );

        // Start rendering
        ?>
        <div class="wrap kan__container">
            <?php
            // Use standard header with custom text
            if (function_exists('kanews_render_admin_header')) {
                kanews_render_admin_header('kai', esc_html(get_bloginfo('name')) . ' · KAI');
            } else {
                // Fallback to custom header if function doesn't exist
                ?>
            <div class="kan__header">
                <div class="kan__header-container">
                    <div class="kan__header-title">
                        <p><?php echo esc_html(get_bloginfo('name')); ?> · KAI</p>
                    </div>
                    <div class="kan__header-text"><?php esc_html_e('Kanews temasını kendi zevkinize göre şekilendirmeye hemen başlayabilirsiniz.', 'kanews'); ?></div>
                </div>
                    <?php
                    if (function_exists('kanews_admin_tab_2')) {
                        kanews_admin_tab_2('', '', '', '', '', '', 'nav-tab-active');
                    }
                    ?>
            </div>
                <?php
            }
            ?>
            <?php
            $intervalLabels = array(
                'quarterhourly' => __('15 dakikada bir', 'kanews'),
                'half-hourly'   => __('30 dakikada bir', 'kanews'),
                'hourly'        => __('Saatte bir', 'kanews'),
                'twicedaily'    => __('Günde iki kez', 'kanews'),
                'daily'         => __('Günde bir', 'kanews'),
            );
            $intervalLabel = isset($intervalLabels[$currentInterval]) ? $intervalLabels[$currentInterval] : __('Planlanmadı', 'kanews');
            $activeFeedsCount = is_array($feeds) ? count($feeds) : 0;
            $audioStatus = $audioEnabled ? __('Aktif', 'kanews') : __('Pasif', 'kanews');
            $kaiStats = array(
                array(
                    'label' => __('Aktif Bot', 'kanews'),
                    'value' => number_format_i18n($activeFeedsCount),
                    'hint'  => $activeFeedsCount ? __('Planlanan görevler hazır', 'kanews') : __('Henüz bot oluşturulmadı', 'kanews'),
                ),
                array(
                    'label' => __('Cron Aralığı', 'kanews'),
                    'value' => $intervalLabel,
                    'hint'  => __('Otomatik çalışma planı', 'kanews'),
                ),
                array(
                    'label' => __('Haber Bülteni', 'kanews'),
                    'value' => $audioStatus,
                    'hint'  => $audioEnabled ? sprintf(__('Günlük %s kayıt', 'kanews'), intval($audioDailyCount)) : __('Devre dışı bırakıldı', 'kanews'),
                ),
            );
   
            ?>

            <div class="kai-dashboard">
                <?php
                if ( function_exists( 'kanews_render_admin_hero' ) ) {
                    kanews_render_admin_hero(
                        array(
                            'eyebrow'      => __( 'KAI Yapay Zeka Merkezi', 'kanews' ),
                            'title'        => sprintf( '%s · KAI', esc_html( get_bloginfo( 'name' ) ) ),
                            'description'  => __( 'KAI ile haberlerinizi özgünleştirin, görsel üretin ve sesli haber bültenini yayına hazır hale getirin.', 'kanews' ),
                            'tags'         => array(
                                array(
                                    'value' => esc_html( date_i18n( get_option( 'date_format' ) ) ),
                                    'label' => __( 'Son kontrol', 'kanews' ),
                                ),
                                array(
                                    'value' => $apiStatusLabel,
                                    'label' => __( 'API durumu', 'kanews' ),
                                ),
                            ),
                            'stats'        => $kaiStats,
                            'class'        => 'kanews-hero--kai',
                            'actions'      => array(
                                array(
                                    'label' => __( 'Ayarları Aç', 'kanews' ),
                                    'href'  => '#' . $kaiSettingsId,
                                    'class' => 'button button-primary',
                                    'attrs' => array(
                                        'data-target' => $kaiSettingsId,
                                        'id'          => 'kaiSettingsBtn',
                                    ),
                                ),
                                array(
                                    'label' => __( 'Haber Botu', 'kanews' ),
                                    'href'  => '#' . $kaiFeedsId,
                                    'class' => 'button',
                                    'attrs' => array(
                                        'data-target' => $kaiFeedsId,
                                        'id'          => 'kaiFeedsBtn',
                                    ),
                                ),
                                array(
                                    'label' => __( 'Haber Bülteni', 'kanews' ),
                                    'href'  => '#' . $kaiAudioId,
                                    'class' => 'button',
                                    'attrs' => array(
                                        'data-target' => $kaiAudioId,
                                        'id'          => 'kaiAudioBtn',
                                    ),
                                ),
                            ),
                        )
                    );
                } else {
                    ?>
                    <section class="kanews-hero kanews-hero--kai">
                        <div class="kanews-hero__pattern kanews-hero__pattern--one"></div>
                        <div class="kanews-hero__pattern kanews-hero__pattern--two"></div>
                        <div class="kanews-hero__body">
                            <p class="kanews-hero__eyebrow"><?php esc_html_e('KAI Yapay Zeka Merkezi', 'kanews'); ?></p>
                            <h1 class="kanews-hero__title"><?php echo esc_html(get_bloginfo('name')); ?> · KAI</h1>
                            <p class="kanews-hero__desc"><?php esc_html_e('KAI ile haberlerinizi özgünleştirin, görsel üretin ve sesli haber bültenini yayına hazır hale getirin.', 'kanews'); ?></p>
                            <div class="kanews-hero__meta">
                                <span><?php esc_html_e( 'Son kontrol:', 'kanews' ); ?> <?php echo esc_html( date_i18n( get_option( 'date_format' ) ) ); ?></span>
                </div>
                            <div class="kanews-hero__actions">
                                <a href="#<?php echo esc_attr($kaiSettingsId); ?>" data-target="<?php echo esc_attr($kaiSettingsId); ?>" class="button button-primary"><?php esc_html_e('Ayarları Aç', 'kanews'); ?></a>
                                <a href="#<?php echo esc_attr($kaiFeedsId); ?>" data-target="<?php echo esc_attr($kaiFeedsId); ?>" class="button"><?php esc_html_e('Haber Botu', 'kanews'); ?></a>
                                <a href="#<?php echo esc_attr($kaiAudioId); ?>" data-target="<?php echo esc_attr($kaiAudioId); ?>" class="button"><?php esc_html_e('Haber Bülteni', 'kanews'); ?></a>
                        </div>
                    </div>
                        <div class="kanews-hero__stats">
                            <?php foreach ( $kaiStats as $stat ) : ?>
                                <div class="kanews-hero__stat">
                                    <span class="kanews-hero__stat-label"><?php echo esc_html( $stat['label'] ); ?></span>
                                    <span class="kanews-hero__stat-value"><?php echo esc_html( $stat['value'] ); ?></span>
                                    <span class="kanews-hero__stat-hint"><?php echo esc_html( $stat['hint'] ); ?></span>
                </div>
                            <?php endforeach; ?>
            </div>
                    </section>
                    <?php
                }
                ?>

            </div>

            <?php if ($notice && !empty($notice['message'])) : ?>
                <div class="notice notice-<?php echo $notice['type'] === 'error' ? 'error' : 'success'; ?> is-dismissible">
                    <p><?php echo esc_html($notice['message']); ?></p>
                </div>
            <?php endif; ?>

            <?php $this->renderSettingsSection($kaiSettingsId, $currentInterval, $openaiApi, $pexelsApi, $chatActive, $chatTitle, $chatPlaceholder, $chatFreeLimit, $chatPremiumLimit, $chatTextWelcomeFree, $chatTextWelcomePremium, $chatTextRemainingFree, $chatTextRemainingPremium, $chatTextUpgrade); ?>
            <?php $this->renderFeedsSection($kaiFeedsId, $feeds, $defaultAuthor, $defaultStatus, $feedImageSources, $defaultFeedImageSource, $feedAiModels, $defaultFeedAiModel, $editingFeed); ?>
            <?php $this->renderAudioSection($kaiAudioId, $currentInterval, $openaiApi, $pexelsApi, $chatActive, $chatTitle, $chatPlaceholder, $chatFreeLimit, $chatPremiumLimit, $chatTextWelcomeFree, $chatTextWelcomePremium, $chatTextRemainingFree, $chatTextRemainingPremium, $chatTextUpgrade, $audioEnabled, $audioPaused, $audioVoice, $audioDailyCount, $audioHeroEyebrow, $audioHeroTitle, $audioHeroDesc, $availableVoices); ?>
        </div>
        <?php
    }

    private function renderSettingsSection($kaiSettingsId, $currentInterval, $openaiApi, $pexelsApi, $chatActive, $chatTitle, $chatPlaceholder, $chatFreeLimit, $chatPremiumLimit, $chatTextWelcomeFree, $chatTextWelcomePremium, $chatTextRemainingFree, $chatTextRemainingPremium, $chatTextUpgrade): void
    {
        ?>
        <div class="card kai-section kai-settings is-hidden" id="<?php echo esc_attr($kaiSettingsId); ?>" style="max-width:980px;margin-top:10px;padding:24px 32px;">
            <h2 style="margin-top:0">KAI Ayarları</h2>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('kanews_save_kai_settings'); ?>
                <input type="hidden" name="action" value="kanews_save_kai_settings">
                <table class="form-table" role="presentation">
                    <tbody>
                        <tr>
                            <th scope="row"><label for="kai_cron_interval"><?php esc_html_e('Çalışma Sıklığı (Cron)', 'kanews'); ?></label></th>
                            <td>
                                <select id="kai_cron_interval" name="kai_cron_interval">
                                    <option value="quarterhourly" <?php selected($currentInterval, 'quarterhourly'); ?>><?php esc_html_e('Her 15 dakikada bir', 'kanews'); ?></option>
                                    <option value="half-hourly" <?php selected($currentInterval, 'half-hourly'); ?>><?php esc_html_e('Her 30 dakikada bir', 'kanews'); ?></option>
                                    <option value="hourly" <?php selected($currentInterval, 'hourly'); ?>><?php esc_html_e('Saatte bir', 'kanews'); ?></option>
                                    <option value="twicedaily" <?php selected($currentInterval, 'twicedaily'); ?>><?php esc_html_e('Günde iki kez', 'kanews'); ?></option>
                                    <option value="daily" <?php selected($currentInterval, 'daily'); ?>><?php esc_html_e('Günde bir', 'kanews'); ?></option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="openai_api">OpenAI API Anahtarı</label></th>
                            <td>
                                <input type="text" id="openai_api" name="openai_api" class="regular-text" value="<?php echo esc_attr($openaiApi); ?>" placeholder="sk-...">
                                <p class="description">Chat/yeniden yazım için kullanılır.</p>
                                <div class="kai-api-test-row">
                                    <button type="button" class="button kanews-ai-test-api" data-provider="openai"><?php esc_html_e('Bağlantıyı Test Et', 'kanews'); ?></button>
                                    <span class="kanews-ai-test-status" data-provider="openai"></span>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gemini_api">Gemini API Anahtarı</label></th>
                            <td>
                                <input type="text" id="gemini_api" name="gemini_api" class="regular-text" value="<?php echo esc_attr(Options::getApiKey('gemini')); ?>" placeholder="AIza...">
                                <p class="description">Google Gemini için kullanılır.</p>
                                <div class="kai-api-test-row">
                                    <button type="button" class="button kanews-ai-test-api" data-provider="gemini"><?php esc_html_e('Bağlantıyı Test Et', 'kanews'); ?></button>
                                    <span class="kanews-ai-test-status" data-provider="gemini"></span>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="pexels_api">Pexels API Anahtarı</label></th>
                            <td>
                                <input type="text" id="pexels_api" name="pexels_api" class="regular-text" value="<?php echo esc_attr($pexelsApi); ?>" placeholder="563492ad6f91700001000001...">
                                <p class="description"><?php esc_html_e('Görsel kaynağı Pexels seçildiğinde gereklidir.', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">KAI Sohbet Sistemi</th>
                            <td>
                                <label><input type="checkbox" name="kai_chat_active" value="1" <?php checked($chatActive, true); ?>> Aktif</label>
                                <p class="description">Makale sayfalarında sohbet penceresini göster.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_title">Sohbet Başlığı</label></th>
                            <td><input type="text" id="kai_chat_title" name="kai_chat_title" class="regular-text" value="<?php echo esc_attr($chatTitle); ?>"></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_placeholder">Placeholder</label></th>
                            <td><input type="text" id="kai_chat_placeholder" name="kai_chat_placeholder" class="regular-text" value="<?php echo esc_attr($chatPlaceholder); ?>"></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_free_limit">Ücretsiz Limit</label></th>
                            <td><input type="number" id="kai_chat_free_limit" name="kai_chat_free_limit" class="small-text" value="<?php echo esc_attr($chatFreeLimit); ?>" min="0"></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_premium_limit">Premium Limit</label></th>
                            <td><input type="number" id="kai_chat_premium_limit" name="kai_chat_premium_limit" class="small-text" value="<?php echo esc_attr($chatPremiumLimit); ?>" min="0"></td>
                        </tr>
                        <tr>
                            <th scope="row" colspan="2">
                                <h3 style="margin:20px 0 10px 0;"><?php esc_html_e('KAI Sohbet Metinleri', 'kanews'); ?></h3>
                            </th>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_text_welcome_free"><?php esc_html_e('Hoş Geldiniz (Ücretsiz)', 'kanews'); ?></label></th>
                            <td>
                                <textarea id="kai_chat_text_welcome_free" name="kai_chat_text_welcome_free" class="large-text" rows="3"><?php echo esc_textarea($chatTextWelcomeFree); ?></textarea>
                                <p class="description"><?php esc_html_e('Değişkenler: {free_limit}', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_text_welcome_premium"><?php esc_html_e('Hoş Geldiniz (Premium)', 'kanews'); ?></label></th>
                            <td>
                                <textarea id="kai_chat_text_welcome_premium" name="kai_chat_text_welcome_premium" class="large-text" rows="3"><?php echo esc_textarea($chatTextWelcomePremium); ?></textarea>
                                <p class="description"><?php esc_html_e('Değişkenler: {premium_limit}', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_text_remaining_free"><?php esc_html_e('Kalan Hakkı (Ücretsiz)', 'kanews'); ?></label></th>
                            <td>
                                <textarea id="kai_chat_text_remaining_free" name="kai_chat_text_remaining_free" class="large-text" rows="3"><?php echo esc_textarea($chatTextRemainingFree); ?></textarea>
                                <p class="description"><?php esc_html_e('Değişkenler: {remaining}, {upgrade_url}', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_text_remaining_premium"><?php esc_html_e('Kalan Hakkı (Premium)', 'kanews'); ?></label></th>
                            <td>
                                <textarea id="kai_chat_text_remaining_premium" name="kai_chat_text_remaining_premium" class="large-text" rows="3"><?php echo esc_textarea($chatTextRemainingPremium); ?></textarea>
                                <p class="description"><?php esc_html_e('Değişkenler: {remaining}', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_chat_text_upgrade"><?php esc_html_e('Yükseltme Mesajı', 'kanews'); ?></label></th>
                            <td>
                                <textarea id="kai_chat_text_upgrade" name="kai_chat_text_upgrade" class="large-text" rows="3"><?php echo esc_textarea($chatTextUpgrade); ?></textarea>
                                <p class="description"><?php esc_html_e('Değişkenler: {upgrade_url}', 'kanews'); ?></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <?php submit_button(__('Ayarları Kaydet', 'kanews')); ?>
            </form>
        </div>
        <?php
    }

    private function renderFeedsSection($kaiFeedsId, $feeds, $defaultAuthor, $defaultStatus, array $imageSourceOptions, string $defaultFeedImageSource, array $feedAiModels, string $defaultFeedAiModel, ?array $editingFeed): void
    {
        ?>
        <div class="card kai-section kai-feeds is-hidden" id="<?php echo esc_attr($kaiFeedsId); ?>" style="max-width:980px;margin-top:20px;padding:24px 32px;">
            <h2><?php esc_html_e('Yeni Feed Ekle', 'kanews'); ?></h2>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('kanews_add_kai_feed'); ?>
                <input type="hidden" name="action" value="kanews_add_kai_feed">
                <table class="form-table" role="presentation">
                    <tbody>
                        <tr>
                            <th scope="row"><label for="feed_title"><?php esc_html_e('Feed Başlığı (isteğe bağlı)', 'kanews'); ?></label></th>
                            <td>
                                <input name="feed_title" id="feed_title" type="text" class="regular-text" placeholder="<?php esc_attr_e('Kaynağı hatırlatacak kısa bir isim', 'kanews'); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="feed_url"><?php esc_html_e('Feed URL', 'kanews'); ?></label></th>
                            <td>
                                <input name="feed_url" id="feed_url" type="url" class="regular-text" placeholder="https://example.com/feed" required>
                                <p class="description"><?php esc_html_e('Tam RSS/Atom feed adresini girin.', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="feed_max_items"><?php esc_html_e('Her çalıştırmada yazı sayısı', 'kanews'); ?></label></th>
                            <td>
                                <input name="feed_max_items" id="feed_max_items" type="number" min="1" max="10" value="3" class="small-text">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Anlatım Biçimi', 'kanews'); ?></th>
                            <td>
                                <fieldset>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="feed_use_5w1h" value="1"> <?php esc_html_e('5N1K Formatı Kullan', 'kanews'); ?>
                                    </label>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="feed_add_faq" value="1"> <?php esc_html_e('SSS Bölümü Ekle', 'kanews'); ?>
                                    </label>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="feed_use_tables" value="1"> <?php esc_html_e('Karşılaştırma Tabloları Kullan', 'kanews'); ?>
                                    </label>
                                    <label style="display:block;margin-bottom:0;">
                                        <input type="checkbox" name="feed_use_list" value="1"> <?php esc_html_e('Listeler Kullan', 'kanews'); ?>
                                    </label>
                                </fieldset>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="feed_post_status"><?php esc_html_e('Yazı durumu', 'kanews'); ?></label></th>
                            <td>
                                <select name="feed_post_status" id="feed_post_status">
                                    <option value="publish"><?php esc_html_e('Yayınla', 'kanews'); ?></option>
                                    <option value="draft"><?php esc_html_e('Taslak olarak kaydet', 'kanews'); ?></option>
                                    <option value="pending"><?php esc_html_e('İnceleme bekliyor', 'kanews'); ?></option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="feed_author"><?php esc_html_e('Yazarı', 'kanews'); ?></label></th>
                            <td>
                                <?php
                                wp_dropdown_users([
                                    'name' => 'feed_author',
                                    'selected' => $defaultAuthor,
                                    'role__in' => ['administrator', 'editor', 'author'],
                                    'show_option_none' => false,
                                ]);
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="feed_ai_model"><?php esc_html_e('Yapay Zeka Modeli', 'kanews'); ?></label></th>
                            <td>
                                <select name="feed_ai_model" id="feed_ai_model">
                                    <?php foreach ($feedAiModels as $value => $label) : ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($defaultFeedAiModel, $value); ?>>
                                            <?php echo esc_html($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">
                                    <?php esc_html_e('Bu feed için içerik üretiminde kullanılacak modeli seçin. Yalnızca API anahtarı tanımlı sağlayıcılar görünür.', 'kanews'); ?>
                                </p>
                                <?php if (count($feedAiModels) <= 1) : ?>
                                    <p class="description" style="color:#d63638;">
                                        <?php esc_html_e('Farklı modeller göremiyorsanız OpenAI veya Gemini API anahtarlarınızı ayarlar sekmesinden ekleyin.', 'kanews'); ?>
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Feed durumu', 'kanews'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="feed_active" value="1" checked>
                                    <?php esc_html_e('Feed eklendikten sonra otomatik olarak aktif olsun', 'kanews'); ?>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="feed_image_source"><?php esc_html_e('Görsel Kaynağı', 'kanews'); ?></label></th>
                            <td>
                                <select name="feed_image_source" id="feed_image_source">
                                    <?php foreach ($imageSourceOptions as $value => $label) : ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($defaultFeedImageSource, $value); ?>>
                                            <?php echo esc_html($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

                                <?php if (count(array_diff(array_keys($imageSourceOptions), ['none'])) === 0) : ?>
                                    <p class="description" style="color:#d63638;">
                                        <?php esc_html_e('OpenAI, Gemini veya Pexels API anahtarı eklediğinizde otomatik görsel üretim seçenekleri aktif olur.', 'kanews'); ?>
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <?php submit_button(__('Feed Ekle', 'kanews')); ?>
            </form>

            <?php if ($editingFeed): ?>
                <h2 style="margin-top:40px;"><?php esc_html_e('Feed Düzenle', 'kanews'); ?></h2>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-bottom:40px;">
                    <?php wp_nonce_field('kanews_edit_kai_feed_' . $editingFeed['id']); ?>
                    <input type="hidden" name="action" value="kanews_edit_kai_feed">
                    <input type="hidden" name="feed_id" value="<?php echo esc_attr($editingFeed['id']); ?>">
                    <table class="form-table" role="presentation">
                        <tbody>
                            <tr>
                                <th scope="row"><label for="edit_feed_title"><?php esc_html_e('Feed Başlığı', 'kanews'); ?></label></th>
                                <td>
                                    <input name="feed_title" id="edit_feed_title" type="text" class="regular-text" value="<?php echo esc_attr($editingFeed['title'] ?? ''); ?>">
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="edit_feed_url"><?php esc_html_e('Feed URL', 'kanews'); ?></label></th>
                                <td>
                                    <input name="feed_url" id="edit_feed_url" type="url" class="regular-text" value="<?php echo esc_attr($editingFeed['url'] ?? ''); ?>" required>
                                    <p class="description"><?php esc_html_e('Tam RSS/Atom feed adresini girin.', 'kanews'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="edit_feed_max_items"><?php esc_html_e('Her çalıştırmada yazı sayısı', 'kanews'); ?></label></th>
                                <td>
                                    <input name="feed_max_items" id="edit_feed_max_items" type="number" min="1" max="10" value="<?php echo esc_attr($editingFeed['max_items'] ?? 3); ?>" class="small-text">
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="edit_feed_post_status"><?php esc_html_e('Yazı durumu', 'kanews'); ?></label></th>
                                <td>
                                    <select name="feed_post_status" id="edit_feed_post_status">
                                        <?php foreach (['publish' => __('Yayınla', 'kanews'), 'draft' => __('Taslak', 'kanews'), 'pending' => __('İnceleme', 'kanews')] as $value => $label): ?>
                                            <option value="<?php echo esc_attr($value); ?>" <?php selected(($editingFeed['post_status'] ?? $defaultStatus), $value); ?>>
                                                <?php echo esc_html($label); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="edit_feed_author"><?php esc_html_e('Yazarı', 'kanews'); ?></label></th>
                                <td>
                                    <?php
                                    wp_dropdown_users([
                                        'name' => 'feed_author',
                                        'selected' => $editingFeed['post_author'] ?? $defaultAuthor,
                                        'role__in' => ['administrator', 'editor', 'author'],
                                        'show_option_none' => false,
                                        'id' => 'edit_feed_author',
                                    ]);
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="edit_feed_ai_model"><?php esc_html_e('Yapay Zeka Modeli', 'kanews'); ?></label></th>
                                <td>
                                    <select name="feed_ai_model" id="edit_feed_ai_model">
                                        <?php foreach ($feedAiModels as $value => $label): ?>
                                            <option value="<?php echo esc_attr($value); ?>" <?php selected(($editingFeed['model'] ?? $defaultFeedAiModel), $value); ?>>
                                                <?php echo esc_html($label); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Feed durumu', 'kanews'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="feed_active" value="1" <?php checked(!empty($editingFeed['active'])); ?>>
                                        <?php esc_html_e('Feed aktif', 'kanews'); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Anlatım Biçimi', 'kanews'); ?></th>
                                <td>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="feed_use_5w1h" value="1" <?php checked(!empty($editingFeed['use_5w1h'])); ?>> <?php esc_html_e('5N1K Formatı Kullan', 'kanews'); ?>
                                    </label>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="feed_add_faq" value="1" <?php checked(!empty($editingFeed['add_faq'])); ?>> <?php esc_html_e('SSS Bölümü Ekle', 'kanews'); ?>
                                    </label>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="feed_use_tables" value="1" <?php checked(!empty($editingFeed['use_tables'])); ?>> <?php esc_html_e('Karşılaştırma Tabloları Kullan', 'kanews'); ?>
                                    </label>
                                    <label style="display:block;margin-bottom:0;">
                                        <input type="checkbox" name="feed_use_list" value="1" <?php checked(!empty($editingFeed['use_list'])); ?>> <?php esc_html_e('Listeler Kullan', 'kanews'); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="edit_feed_image_source"><?php esc_html_e('Görsel Kaynağı', 'kanews'); ?></label></th>
                                <td>
                                    <select name="feed_image_source" id="edit_feed_image_source">
                                        <?php foreach ($imageSourceOptions as $value => $label): ?>
                                            <option value="<?php echo esc_attr($value); ?>" <?php selected(($editingFeed['image_source'] ?? $defaultFeedImageSource), $value); ?>>
                                                <?php echo esc_html($label); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <?php submit_button(__('Feed\'i Güncelle', 'kanews')); ?>
                </form>

                <h3 style="margin-top:30px;"><?php esc_html_e('Bu feed ile oluşturulan son haberler', 'kanews'); ?></h3>
                <?php
                $feedPosts = get_posts([
                    'post_type'      => 'post',
                    'posts_per_page' => 10,
                    'post_status'    => ['publish', 'draft', 'pending', 'future'],
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                    'meta_key'       => '_kai_feed_id',
                    'meta_value'     => $editingFeed['id'],
                ]);
                if (empty($feedPosts)) :
                    ?>
                    <p><?php esc_html_e('Bu feed ile henüz haber oluşturulmamış.', 'kanews'); ?></p>
                <?php else : ?>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Başlık', 'kanews'); ?></th>
                                <th><?php esc_html_e('Tarih', 'kanews'); ?></th>
                                <th><?php esc_html_e('Durum', 'kanews'); ?></th>
                                <th><?php esc_html_e('İşlemler', 'kanews'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($feedPosts as $post) : ?>
                                <tr>
                                    <td>
                                        <a href="<?php echo esc_url(get_edit_post_link($post->ID)); ?>">
                                            <?php echo esc_html(get_the_title($post)); ?>
                                        </a>
                                    </td>
                                    <td><?php echo esc_html(get_the_date('', $post)); ?></td>
                                    <td><?php echo esc_html(get_post_status_object($post->post_status)->label ?? $post->post_status); ?></td>
                                    <td>
                                        <a class="button button-small" href="<?php echo esc_url(get_edit_post_link($post->ID)); ?>">
                                            <?php esc_html_e('Düzenle', 'kanews'); ?>
                                        </a>
                                        <a class="button button-small" href="<?php echo esc_url(get_permalink($post->ID)); ?>" target="_blank" rel="noopener">
                                            <?php esc_html_e('Görüntüle', 'kanews'); ?>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            <?php endif; ?>

            <h2 style="margin-top:40px;"><?php esc_html_e('Feed Listesi', 'kanews'); ?></h2>
            <?php if (empty($feeds)) : ?>
                <p><?php esc_html_e('Henüz feed eklenmedi. Üstteki formu kullanarak ilk feed\'inizi ekleyin.', 'kanews'); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Başlık', 'kanews'); ?></th>
                            <th><?php esc_html_e('URL', 'kanews'); ?></th>
                            <th><?php esc_html_e('Durum', 'kanews'); ?></th>
                            <th><?php esc_html_e('Son Çalışma', 'kanews'); ?></th>
                            <th><?php esc_html_e('Sonuç', 'kanews'); ?></th>
                            <th style="width:220px;"><?php esc_html_e('İşlemler', 'kanews'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($feeds as $feed) :
                            $isActive = !empty($feed['active']);
                            $lastRun = isset($feed['last_run']) && $feed['last_run']
                                ? sprintf(
                                    esc_html__('%s önce', 'kanews'),
                                    human_time_diff((int) $feed['last_run'], current_time('timestamp'))
                                )
                                : esc_html__('Henüz çalışmadı', 'kanews');
                            $lastResult = '';
                            if (!empty($feed['last_post_count'])) {
                                $lastResult = sprintf(esc_html__('%d yeni yazı', 'kanews'), (int) $feed['last_post_count']);
                            } elseif (!empty($feed['stats']['skipped'])) {
                                $lastResult = sprintf(esc_html__('%d içerik atlandı', 'kanews'), (int) $feed['stats']['skipped']);
                            } else {
                                $lastResult = '—';
                            }
                            if (!empty($feed['last_error'])) {
                                $lastResult .= '<br><span class="description" style="color:#d63638;">' . esc_html($feed['last_error']) . '</span>';
                            }

                            $toggleUrl = wp_nonce_url(
                                admin_url('admin-post.php?action=kanews_toggle_kai_feed&feed_id=' . rawurlencode($feed['id']) . '&state=' . ($isActive ? '0' : '1')),
                                'kanews_toggle_kai_feed_' . $feed['id']
                            );

                            $deleteUrl = wp_nonce_url(
                                admin_url('admin-post.php?action=kanews_delete_kai_feed&feed_id=' . rawurlencode($feed['id'])),
                                'kanews_delete_kai_feed_' . $feed['id']
                            );

                            $runUrl = wp_nonce_url(
                                admin_url('admin-post.php?action=kanews_run_kai_feed&feed_id=' . rawurlencode($feed['id'])),
                                'kanews_run_kai_feed_' . $feed['id']
                            );
                            $imageSourceLabel = $this->manager->feeds()->imageSourceLabel($feed['image_source'] ?? '');
                            $modelLabel = $this->manager->feeds()->aiModelLabel($feed['model'] ?? '');
                            $editUrl = admin_url('admin.php?page=kanews-kai&edit_feed=' . rawurlencode($feed['id']) . '#kai-feeds');
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo esc_html($feed['title'] ?: '—'); ?></strong>
                                    <div class="description">
                                        <?php echo esc_html($feed['max_items'] ?? 3); ?> <?php esc_html_e('öğe / çalıştırma', 'kanews'); ?>
                                        · <?php echo esc_html($feed['post_status'] ?? $defaultStatus); ?>
                                        · <?php esc_html_e('Görsel', 'kanews'); ?>: <?php echo esc_html($imageSourceLabel); ?>
                                        · <?php esc_html_e('Model', 'kanews'); ?>: <?php echo esc_html($modelLabel); ?>
                                    </div>
                                </td>
                                <td><a href="<?php echo esc_url($feed['url']); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($feed['url']); ?></a></td>
                                <td>
                                    <?php if ($isActive) : ?>
                                        <span class="dashicons dashicons-yes-alt" style="color:#198754;"></span> <?php esc_html_e('Aktif', 'kanews'); ?>
                                    <?php else : ?>
                                        <span class="dashicons dashicons-minus" style="color:#d63638;"></span> <?php esc_html_e('Pasif', 'kanews'); ?>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($lastRun); ?></td>
                                <td><?php echo wp_kses_post($lastResult); ?></td>
                                <td>
                                    <a class="button button-small" href="<?php echo esc_url($toggleUrl); ?>">
                                        <?php echo $isActive ? esc_html__('Durdur', 'kanews') : esc_html__('Aktifleştir', 'kanews'); ?>
                                    </a>
                                    <a class="button button-small" href="<?php echo esc_url($runUrl); ?>">
                                        <?php esc_html_e('Hemen Çalıştır', 'kanews'); ?>
                                    </a>
                                    <a class="button button-small" href="<?php echo esc_url($editUrl); ?>">
                                        <?php esc_html_e('Düzenle', 'kanews'); ?>
                                    </a>
                                    <a class="button button-small button-link-delete" href="<?php echo esc_url($deleteUrl); ?>" onclick="return confirm('<?php echo esc_js(__('Bu feed tamamen silinecek. Devam etmek istiyor musunuz?', 'kanews')); ?>');">
                                        <?php esc_html_e('Sil', 'kanews'); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    private function renderAudioSection($kaiAudioId, $currentInterval, $openaiApi, $pexelsApi, $chatActive, $chatTitle, $chatPlaceholder, $chatFreeLimit, $chatPremiumLimit, $chatTextWelcomeFree, $chatTextWelcomePremium, $chatTextRemainingFree, $chatTextRemainingPremium, $chatTextUpgrade, $audioEnabled, $audioPaused, $audioVoice, $audioDailyCount, $audioHeroEyebrow, $audioHeroTitle, $audioHeroDesc, $availableVoices): void
    {
        $openaiMissing = empty($openaiApi);
        $settingsAnchor = admin_url('admin.php?page=kanews-kai#kai-settings');
        ?>
        <div class="card kai-section kai-audio is-hidden" id="<?php echo esc_attr($kaiAudioId); ?>" style="max-width:980px;margin-top:20px;padding:24px 32px;">
            <h2><?php esc_html_e('Haber Bülteni', 'kanews'); ?></h2>
            <p><?php esc_html_e('KAI, seçilen ses ve slotlara göre gün içinde otomatik haber bülteni dosyaları üretir. Aşağıdan sistemi yönetebilir ve oluşturulan bültenleri görebilirsiniz.', 'kanews'); ?></p>

            <?php if ($openaiMissing) : ?>
                <div class="notice notice-error" style="margin:16px 0;">
                    <p>
                        <?php echo esc_html__('Sesli haber bülteni için OpenAI TTS gerekir. Lütfen önce OpenAI API anahtarını ekleyin. Gemini şu anda bu görev için desteklenmiyor.', 'kanews'); ?>
                    </p>
                    <p>
                        <a class="button button-primary" href="<?php echo esc_url($settingsAnchor); ?>">
                            <?php esc_html_e('API Anahtarı Ekle', 'kanews'); ?>
                        </a>
                    </p>
                </div>
            <?php endif; ?>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:20px;">
                <?php wp_nonce_field('kanews_save_kai_settings'); ?>
                <input type="hidden" name="action" value="kanews_save_kai_settings">
                <input type="hidden" name="kai_audio_panel" value="1">
                <input type="hidden" name="kai_cron_interval" value="<?php echo esc_attr($currentInterval); ?>">
                <input type="hidden" name="openai_api" value="<?php echo esc_attr($openaiApi); ?>">
                <input type="hidden" name="pexels_api" value="<?php echo esc_attr($pexelsApi); ?>">
                <input type="hidden" name="kai_chat_active" value="<?php echo $chatActive ? 1 : 0; ?>">
                <input type="hidden" name="kai_chat_title" value="<?php echo esc_attr($chatTitle); ?>">
                <input type="hidden" name="kai_chat_placeholder" value="<?php echo esc_attr($chatPlaceholder); ?>">
                <input type="hidden" name="kai_chat_free_limit" value="<?php echo esc_attr($chatFreeLimit); ?>">
                <input type="hidden" name="kai_chat_premium_limit" value="<?php echo esc_attr($chatPremiumLimit); ?>">
                <input type="hidden" name="kai_chat_text_welcome_free" value="<?php echo esc_attr($chatTextWelcomeFree); ?>">
                <input type="hidden" name="kai_chat_text_welcome_premium" value="<?php echo esc_attr($chatTextWelcomePremium); ?>">
                <input type="hidden" name="kai_chat_text_remaining_free" value="<?php echo esc_attr($chatTextRemainingFree); ?>">
                <input type="hidden" name="kai_chat_text_remaining_premium" value="<?php echo esc_attr($chatTextRemainingPremium); ?>">
                <input type="hidden" name="kai_chat_text_upgrade" value="<?php echo esc_attr($chatTextUpgrade); ?>">
                <table class="form-table" role="presentation">
                    <tbody>
                        <tr>
                            <th scope="row"><?php esc_html_e('Görev Durumu', 'kanews'); ?></th>
                            <td>
                                <label>
                                    <input type="hidden" name="kai_audio_enabled" value="0">
                                    <input type="checkbox" name="kai_audio_enabled" value="1" <?php checked($audioEnabled, true); ?> <?php disabled($openaiMissing, true); ?>>
                                    <?php esc_html_e('Sesli haber bülteni sistemini aktif et', 'kanews'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('Pasif olduğunda cron tetiklenmez ve yeni ses dosyası oluşturulmaz.', 'kanews'); ?>
                                    <?php if ($openaiMissing) : ?>
                                        <br><?php esc_html_e('OpenAI API anahtarı olmadan görev aktifleştirilemez. Lütfen KAI Ayarları sekmesinden anahtarı ekleyin.', 'kanews'); ?>
                                    <?php endif; ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Üretimi Durdur', 'kanews'); ?></th>
                            <td>
                                <label>
                                    <input type="hidden" name="kai_audio_paused" value="0">
                                    <input type="checkbox" name="kai_audio_paused" value="1" <?php checked($audioPaused, true); ?>>
                                    <?php esc_html_e('Yeni ses dosyası oluşturma, mevcut bültenler görünür kalsın', 'kanews'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('Sistem aktif kalır, slotlar ve sayfa görünür; ancak yeni TTS dosyası üretilmez.', 'kanews'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_audio_voice"><?php esc_html_e('Seslendirme Sesi', 'kanews'); ?></label></th>
                            <td>
                                <select id="kai_audio_voice" name="kai_audio_voice">
                                    <?php foreach ($availableVoices as $voiceKey => $voiceLabel) : ?>
                                        <option value="<?php echo esc_attr($voiceKey); ?>" <?php selected($audioVoice, $voiceKey); ?>>
                                            <?php echo esc_html($voiceLabel); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_audio_daily_count"><?php esc_html_e('Günlük Özet Sayısı', 'kanews'); ?></label></th>
                            <td>
                                <input type="number" id="kai_audio_daily_count" name="kai_audio_daily_count" class="small-text" value="<?php echo esc_attr($audioDailyCount); ?>" min="1" max="3">
                                <p class="description"><?php esc_html_e('1=Sabah, 2=Sabah+Öğle, 3=Sabah+Öğle+Akşam slotları sırasıyla kullanılır.', 'kanews'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_audio_hero_eyebrow"><?php esc_html_e('Sayfa Üst Başlığı', 'kanews'); ?></label></th>
                            <td>
                                <input type="text" id="kai_audio_hero_eyebrow" name="kai_audio_hero_eyebrow" class="regular-text" value="<?php echo esc_attr($audioHeroEyebrow); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_audio_hero_title"><?php esc_html_e('Sayfa Başlığı', 'kanews'); ?></label></th>
                            <td>
                                <input type="text" id="kai_audio_hero_title" name="kai_audio_hero_title" class="regular-text" value="<?php echo esc_attr($audioHeroTitle); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="kai_audio_hero_desc"><?php esc_html_e('Sayfa Açıklaması', 'kanews'); ?></label></th>
                            <td>
                                <textarea id="kai_audio_hero_desc" name="kai_audio_hero_desc" class="large-text" rows="3"><?php echo esc_textarea($audioHeroDesc); ?></textarea>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Shortcode', 'kanews'); ?></th>
                            <td>
                                <code>[kai_audio_briefings limit="6"]</code>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <?php submit_button(__('Kaydet', 'kanews')); ?>
            </form>

            <hr style="margin:30px 0;">
            <h3><?php esc_html_e('Haber Bültenleri', 'kanews'); ?></h3>
            <?php
            $latestAudio = get_posts([
                'post_type' => 'kai_audio_brief',
                'posts_per_page' => 10,
                'post_status' => 'any',
                'orderby' => 'date',
                'order' => 'DESC',
            ]);
            if (empty($latestAudio)) :
                ?>
                <p><?php esc_html_e('Henüz oluşturulmuş bir ses özeti bulunamadı. Sistem zaman planına göre çalıştığında burada listelenecek.', 'kanews'); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Başlık', 'kanews'); ?></th>
                            <th><?php esc_html_e('Slot', 'kanews'); ?></th>
                            <th><?php esc_html_e('Tarih', 'kanews'); ?></th>
                            <th><?php esc_html_e('Ses Dosyası', 'kanews'); ?></th>
                            <th><?php esc_html_e('İşlemler', 'kanews'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($latestAudio as $audioPost) :
                            $slot = get_post_meta($audioPost->ID, '_kai_audio_slot', true);
                            $date = get_post_meta($audioPost->ID, '_kai_audio_date', true);
                            $file = get_post_meta($audioPost->ID, '_kai_audio_file_url', true);
                            ?>
                            <tr>
                                <td><a href="<?php echo esc_url(get_edit_post_link($audioPost->ID)); ?>"><?php echo esc_html(get_the_title($audioPost)); ?></a></td>
                                <td><?php echo esc_html(kanews_kai_get_audio_slot_label($slot) ?: strtoupper($slot)); ?></td>
                                <td><?php echo esc_html($date ?: get_the_date('', $audioPost)); ?></td>
                                <td>
                                    <?php if ($file) : ?>
                                        <a href="<?php echo esc_url($file); ?>" target="_blank" rel="noopener"><?php esc_html_e('Dinle', 'kanews'); ?></a>
                                    <?php else : ?>
                                        —
                                    <?php endif; ?>
                                </td>
                                <td class="d-flex gap-10">
                                    <?php if ($file) : ?>
                                        <a class="button button-small" href="<?php echo esc_url($file); ?>" target="_blank" rel="noopener"><?php esc_html_e('Dinle', 'kanews'); ?></a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    private function ensureDefaultOptions(): void
    {
        $opts = get_option('kanews_kai_options', []);
        if (!is_array($opts)) {
            $opts = [];
        }

        $defaults = [
            'openai-api' => '',
            'pexels-api' => '',
            'gemini-api' => '',
            'kai-chat-active' => true,
            'kai-chat-title' => 'KAI ile Haber Hakkında Sohbet',
            'kai-chat-placeholder' => 'Sorunuzu yazın...',
            'kai-chat-free-limit' => 5,
            'kai-chat-premium-limit' => 20,
            'kai-chat-text-welcome-free' => 'Hoş geldiniz, günlük {free_limit} yazı için {free_limit}\'er soru sorabilirsiniz.',
            'kai-chat-text-welcome-premium' => 'Hoş geldiniz, Premium üye olarak günlük {premium_limit} yazı için {premium_limit}\'er soru sorabilirsiniz.',
            'kai-chat-text-remaining-free' => 'Ücretsiz kullanıcı olarak {remaining} soru hakkınız kaldı.',
            'kai-chat-text-remaining-premium' => 'Premium üye olarak {remaining} soru hakkınız kaldı.',
            'kai-chat-text-upgrade' => 'Daha fazlası için <a href="{upgrade_url}">üyelik seçeneklerimizi</a> inceleyin.',
            'kai-audio-enabled' => false,
            'kai-audio-voice' => 'alloy',
            'kai-audio-daily-count' => 3,
            'kai-audio-hero-eyebrow' => get_bloginfo('name'),
            'kai-audio-hero-title' => 'Haber Bülteni',
            'kai-audio-hero-description' => 'Günün kritik başlıklarını KAI üç farklı zaman diliminde ses dosyasına dönüştürür. Kulaklığınızı takın, gündemi dakikalar içinde yakalayın.',
        ];

        $changed = false;
        foreach ($defaults as $key => $val) {
            if (!array_key_exists($key, $opts)) {
                $opts[$key] = $val;
                $changed = true;
            }
        }

        if ($changed) {
            update_option('kanews_kai_options', $opts, false);
        }
    }
}

