<?php
/**
 * KAI System - Backward Compatibility Wrapper
 * 
 * This file provides backward compatibility for legacy function calls.
 * All functionality has been moved to class-based architecture.
 * 
 * @package Kanews
 * @subpackage KAI
 */

// Legacy function wrappers for backward compatibility
function calculate_credits_by_post_length($post_content) {
    return \Kanews\Kai\Support\Credits::calculateFromContent($post_content);
}

// Legacy AJAX handlers - now handled by AjaxTaskController
add_action('wp_ajax_generate_tts', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateTts();
});

add_action('wp_ajax_generate_featured_image', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateFeaturedImage();
});

add_action('wp_ajax_generate_comments', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateComments();
});

add_action('wp_ajax_generate_excerpt', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateExcerpt();
});

add_action('wp_ajax_generate_summary', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateSummary();
});

add_action('wp_ajax_generate_seo_title', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateSeoTitle();
});

add_action('wp_ajax_generate_article', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateArticle();
});

add_action('wp_ajax_generate_faq', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateFaq();
});

add_action('wp_ajax_generate_paraphrase', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateParaphrase();
});

add_action('wp_ajax_generate_translate', function() {
    $controller = \Kanews\Kai\Manager::instance();
    $reflection = new ReflectionClass($controller);
    $property = $reflection->getProperty('ajaxController');
    $property->setAccessible(true);
    $ajaxController = $property->getValue($controller);
    $ajaxController->generateTranslate();
});

// Legacy feed functions - now handled by FeedManager
function kanews_kai_get_feed_state() {
    $manager = \Kanews\Kai\Manager::instance();
    return $manager->feeds()->getState();
}

function kanews_kai_save_feed_state($state) {
    $manager = \Kanews\Kai\Manager::instance();
    $manager->feeds()->saveState($state);
}

function kanews_kai_add_notice($type, $message) {
    set_transient('kanews_kai_notice', [
        'type' => $type,
        'message' => $message,
    ], 45);
}

function kanews_kai_maybe_schedule_cron($state = null) {
    $manager = \Kanews\Kai\Manager::instance();
    $manager->feeds()->maybeScheduleCron($state);
}

function kanews_kai_get_audio_slot_label($slot_id) {
    $map = [
        'morning' => __('Sabah Bülteni', 'kanews'),
        'noon'    => __('Öğle Güncellemesi', 'kanews'),
        'evening' => __('Akşam Kapanışı', 'kanews'),
    ];
    return isset($map[$slot_id]) ? $map[$slot_id] : '';
}

function kanews_kai_get_latest_audio_summary() {
    static $in_memory = null;
    if (null !== $in_memory) {
        return $in_memory;
    }

    $cache_key = 'kanews_kai_latest_audio_summary';
    $cached = wp_cache_get($cache_key, 'kanews');

    if (false !== $cached) {
        $in_memory = $cached;
        return $cached;
    }

    $latest_audio = get_posts([
        'post_type'      => 'kai_audio_brief',
        'posts_per_page' => 1,
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC',
        'meta_query'     => [
            [
                'key'     => '_kai_audio_file_url',
                'value'   => '',
                'compare' => '!=',
            ],
        ],
    ]);

    $data = null;

    if (!empty($latest_audio)) {
        $post_id   = $latest_audio[0]->ID;
        $audio_url = get_post_meta($post_id, '_kai_audio_file_url', true);

        if ($audio_url) {
            $slot       = get_post_meta($post_id, '_kai_audio_slot', true);
            $slot_label = kanews_kai_get_audio_slot_label($slot);

            $data = [
                'id'         => $post_id,
                'title'      => get_the_title($post_id),
                'slot_label' => $slot_label ? $slot_label : '',
                'audio_url'  => esc_url_raw($audio_url),
                'permalink'  => get_permalink($post_id),
            ];
        }
    }

    wp_cache_set($cache_key, $data, 'kanews', 5 * MINUTE_IN_SECONDS);
    $in_memory = $data;

    return $data;
}

// Legacy admin page - now handled by AdminUi
function kanews_kai_admin_page() {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    $manager = \Kanews\Kai\Manager::instance();
    $manager->adminUi()->renderAdminPage();
}

function kanews_kai_ensure_default_options() {
    // Ensure defaults exist in dedicated KAI options storage.
    $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-paused'      => false,
        'kai-audio-voice'       => 'alloy',
        'kai-audio-daily-count' => 3,
        'kai-audio-hero-eyebrow'=> get_bloginfo('name'),
        'kai-audio-hero-title'  => 'KAI Haber Bülteni',
        'kai-audio-hero-description' => 'Günün kritik başlıklarını KAI üç farklı zaman diliminde haber bültenine 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);
    }
}
