<?php
// Защита от прямого доступа
if (!defined('ABSPATH')) {
    exit;
}

// Подключение настроек языка
require_once AI_CONTENT_WIZARD_PATH . 'admin/languages.php';
require_once AI_CONTENT_WIZARD_PATH . 'includes/model-helpers.php';

/**
 * Генерирует текст для поста.
 *
 * @param string $post_topic Тема поста.
 * @param string $category_name Название категории.
 * @param string $selected_language Выбранный язык.
 * @param string $keyword Ключевое слово.
 * @param string $format Формат поста.
 * @param string $text_length Длина текста.
 * @param string $site_type Тип сайта.
 * @param string $writing_style Стиль письма.
 * @param string $target_audience Целевая аудитория.
 * @param string $custom_theme Пользовательская тема.
 * @param string $additional_requests Дополнительные запросы.
 * @param string $single_post_additional_request Дополнительные запросы для одного поста.
 * @param string $target_region Целевой регион.
 *
 * @return array Массив с заголовком, контентом и количеством токенов.
 */
function ai_content_wizard_generate_text(
    $post_topic,
    $category_name,
    $selected_language,
    $keyword = '',
    $format = 'post',
    $text_length = '500',
    $site_type = 'store',
    $writing_style = 'formal',
    $target_audience = 'general',
    $custom_theme = '',
    $additional_requests = '',
    $single_post_additional_request = '',
    $target_region = '',
    $related_articles = []
) {
    // Получаем текущую модель с значением по умолчанию
    $text_model = ai_content_wizard_get_setting('ai_content_wizard_text_model', '') ?? '';
    if (!is_string($text_model)) {
        $text_model = '';
    }
    $text_model = trim($text_model);
    $is_openai_model = ai_content_wizard_is_openai_model($text_model);

    // Определяем API-ключ на основе выбранной модели (только OpenAI)
    if ($is_openai_model) {
        // Используем API-ключ OpenAI
        $api_key = ai_content_wizard_get_setting('ai_content_wizard_api_key', '') ?? '';
    } else {
        $api_key = '';
        error_log('AI Content Wizard: No valid OpenAI model detected for "' . $text_model . '".');
    }

    // Проверяем наличие API-ключа
    if (empty($api_key)) {
        error_log('AI Content Wizard: API key for the selected model is empty.');
        return [
            'title'         => __('No title generated', 'ai-content-wizard'),
            'content'       => __('No content generated', 'ai-content-wizard'),
            'input_tokens'  => 0,
            'output_tokens' => 0
        ];
    }

    // Подключаем файлы для OpenAI
    if ($is_openai_model) {
        $openai_files = [
            'includes/text-generation/content/openai/openai_generate_title.php',
            'includes/text-generation/content/openai/openai_enhance_content.php',
            'includes/text-generation/content/openai/openai_generate_content.php',
            'includes/text-generation/ai_content_wizard_text_processing.php'
        ];
        foreach ($openai_files as $file) {
            $file_path = AI_CONTENT_WIZARD_PATH . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            } else {
                error_log("AI Content Wizard: File not found - $file_path");
                return [
                    'title'         => __('No title generated', 'ai-content-wizard'),
                    'content'       => __('No content generated', 'ai-content-wizard'),
                    'input_tokens'  => 0,
                    'output_tokens' => 0
                ];
            }
        }
    } else {
        error_log('AI Content Wizard: No valid OpenAI model found. Check the selected text model.');
        return [
            'title'         => __('No title generated', 'ai-content-wizard'),
            'content'       => __('No content generated', 'ai-content-wizard'),
            'input_tokens'  => 0,
            'output_tokens' => 0
        ];
    }

    // Проверка активного SEO плагина и получение полей
    $seo_fields = ai_content_wizard_check_seo_plugin();
    if (empty($seo_fields)) {
        error_log('AI Content Wizard: No active SEO plugin found.');
        return [
            'title'         => __('No title generated', 'ai-content-wizard'),
            'content'       => __('No content generated', 'ai-content-wizard'),
            'input_tokens'  => 0,
            'output_tokens' => 0
        ];
    }

    // Инициализация недостающих переменных
    $bing_api_key   = ai_content_wizard_get_setting('ai_content_wizard_bing_api_key', '') ?? '';
    $google_api_key = ai_content_wizard_get_setting('ai_content_wizard_google_api_key', '') ?? '';
    $rss_feed_url   = ai_content_wizard_get_setting('ai_content_wizard_rss_feed_url', '') ?? '';
    $today_date     = date('Y-m-d');
    $number         = rand(5, 15);

    // Преобразуем массив $related_articles в строку
    $related_links_str = '';
    if (!empty($related_articles) && is_array($related_articles)) {
        foreach ($related_articles as $ra) {
            if (!empty($ra['title']) && !empty($ra['url'])) {
                $related_links_str .= $ra['title'] . ' - ' . $ra['url'] . "\n";
            }
        }
    }

    // Генерация заголовка статьи через OpenAI
    if ($is_openai_model && function_exists('generate_article_title')) {
        $article_title = generate_article_title(
            sanitize_text_field($post_topic),
            sanitize_text_field($category_name),
            sanitize_text_field($selected_language),
            sanitize_text_field($keyword),
            sanitize_text_field($format),
            sanitize_text_field($custom_theme),
            sanitize_text_field($additional_requests),
            $api_key,
            sanitize_text_field($text_model),
            sanitize_text_field($bing_api_key),
            sanitize_text_field($google_api_key),
            sanitize_text_field($rss_feed_url),
            $today_date,
            $number,
            sanitize_text_field($target_audience),
            sanitize_text_field($target_region),
            sanitize_text_field($writing_style)
        );
    } else {
        error_log('AI Content Wizard: Function for generating article title not found.');
        return [
            'title'         => __('No title generated', 'ai-content-wizard'),
            'content'       => __('No content generated', 'ai-content-wizard'),
            'input_tokens'  => 0,
            'output_tokens' => 0
        ];
    }

    // Генерация основного контента статьи через OpenAI
    if ($is_openai_model && function_exists('generate_article_content')) {
        $article_content = generate_article_content(
            sanitize_text_field($post_topic),
            sanitize_text_field($category_name),
            sanitize_text_field($selected_language),
            sanitize_text_field($keyword),
            sanitize_text_field($format),
            sanitize_text_field($text_length),
            sanitize_text_field($site_type),
            sanitize_text_field($writing_style),
            sanitize_text_field($target_audience),
            sanitize_text_field($custom_theme),
            sanitize_text_field($additional_requests),
            sanitize_text_field($single_post_additional_request),
            $related_links_str,  
            $api_key,
            sanitize_text_field($text_model),			
            sanitize_text_field($target_region),
            $today_date,
            $number,
            sanitize_text_field($bing_api_key),
            sanitize_text_field($google_api_key),
            sanitize_text_field($rss_feed_url)
        );
    } else {
        error_log('AI Content Wizard: Function for generating article content not found.');
        return [
            'title'         => __('No title generated', 'ai-content-wizard'),
            'content'       => __('No content generated', 'ai-content-wizard'),
            'input_tokens'  => 0,
            'output_tokens' => 0
        ];
    }

    // Улучшение качества генерации, если включено (только для OpenAI)
    if (ai_content_wizard_get_setting('ai_content_wizard_enhanced_generation_quality', 0) == 1) {
        if ($is_openai_model && function_exists('enhance_article_content')) {
            $article_content = enhance_article_content(
                $article_content,
                sanitize_text_field($post_topic),
                sanitize_text_field($selected_language),
                $api_key,
                sanitize_text_field($text_model)
            );
        } else {
            error_log('AI Content Wizard: No function found for enhanced content generation.');
        }
    }
    
    // Обработка контента
    if (function_exists('ai_content_wizard_process_text')) {
        $article_content = ai_content_wizard_process_text($article_content);
    }
    
    // Учет использованных токенов
    $total_input_tokens  = strlen($article_title) + strlen($article_content);
    $total_output_tokens = $total_input_tokens;
    
    return [
        'title'         => $article_title,
        'content'       => $article_content,
        'input_tokens'  => $total_input_tokens,
        'output_tokens' => $total_output_tokens
    ];
}
