<?php
if (!defined('ABSPATH')) {
    exit;
}

function enhance_article_content($article_content, $post_topic, $selected_language, $api_key, $text_model) {
    $enhancement_prompt = "The initial draft about '$post_topic' is currently too brief and lacks the depth needed to fully engage and inform readers. To transform this draft into a detailed, engaging, and informative piece, please make the following enhancements directly within the article, ensuring the final content seamlessly incorporates these changes without summarizing them at the end:
    
    1. **Expand the Volume Significantly**: The article needs to be considerably extended to provide a comprehensive overview of '$post_topic'. Aim to triple the current content volume, ensuring the article covers the subject matter thoroughly.
    2. **Add Detailed Sections with Subheadings**: Introduce new sections that explore various aspects of '$post_topic' in depth. Each section should have a relevant subheading and provide detailed insights into the topic.
    3. **Incorporate Tables and Lists**: Use tables to present data or comparisons relevant to '$post_topic' effectively. Also, include bulleted or numbered lists to break down complex information, making it easier for readers to digest.
    4. **Strategically Integrate Links**: Embed at least three internal links to related articles on our website and two external links to authoritative sources. These links should be placed within the sentences of the article where they naturally fit, enhancing the article's value and context without being listed in a separate section.

    Please revise the content below, focusing on integrating these improvements organically into the article. The final piece should not contain a separate summary of the changes made but instead, all enhancements should be naturally part of the article's flow and structure:
    $article_content";

    $response_enhancement = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
        ],
        'body' => json_encode([
            'model' => $text_model,
            'messages' => [['role' => 'system', 'content' => $enhancement_prompt]],
        ]),
        'timeout' => 1000
    ]);

    if (is_wp_error($response_enhancement)) {
        error_log('Error making enhancement request: ' . $response_enhancement->get_error_message());
        return $article_content; // Возвращаем оригинал, если произошла ошибка
    }

    $result_enhancement = json_decode(wp_remote_retrieve_body($response_enhancement), true);
    $enhanced_article_content = $result_enhancement['choices'][0]['message']['content'] ?? $article_content;

    // Удаление всех комментариев и кодов блоков
    $enhanced_article_content = preg_replace('/<!--.*?-->/s', '', $enhanced_article_content);
    $enhanced_article_content = preg_replace('/<h1>.*?<\/h1>/s', '', $enhanced_article_content);
    $enhanced_article_content = preg_replace('/<!DOCTYPE html.*?>/s', '', $enhanced_article_content);
    $enhanced_article_content = preg_replace('/^(<pre.*?>.*?<\/pre>|<code>.*?<\/code>)/s', '', $enhanced_article_content);
    $enhanced_article_content = preg_replace('/(<pre.*?>.*?<\/pre>|<code>.*?<\/code>)$/s', '', $enhanced_article_content);

    return $enhanced_article_content;
}
