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

/**
 * Генерирует SEO теги (теги, тайтл и дескрипшен) с использованием OpenAI.
 */

function generate_seo_tags_openai($content_snippet, $language_full_name, $api_key, $text_model) {
    $tags_prompt = "Analyze the following content snippet in '$language_full_name': \"$content_snippet\". Identify the main themes and topics, then generate a list of 3-5 precise and relevant tags. Each tag should be 1-3 words and reflect the core subject of the content. Output the tags in the same language as the content, separated by commas, without numbering.";
    // Prepare request
    $headers = [
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type'  => 'application/json',
    ];
    $body = json_encode([
        'model'    => $text_model,
        'messages' => [['role' => 'user', 'content' => $tags_prompt]],
    ]);

    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => $headers,
        'body'    => $body,
        'timeout' => 1000,
    ]);

    if (is_wp_error($response)) {
        error_log('OpenAI: Error making request: ' . $response->get_error_message());
        return ['', 0, 0];
    }

    $result = json_decode(wp_remote_retrieve_body($response), true);
    $generated_text = $result['choices'][0]['message']['content'] ?? '';
    $input_tokens = str_word_count($tags_prompt);
    $output_tokens = str_word_count($generated_text);

    // Clean up generated text
    $generated_text = trim($generated_text, '"');
    return [$generated_text, $input_tokens, $output_tokens];
}

function generate_seo_title_description_openai($content_snippet, $format, $language_full_name, $keyword, $site_name, $api_key, $text_model) {
    // Новый промпт для SEO TITLE:
    // Обращаем внимание, что модель должна выбрать один из вариантов спецсимвола или emoji для начала (например, "🔥" или "✅"),
    // включить призыв к действию, обязательно использовать ключевое слово прямо в начале, цифры, а также соблюдать рекомендованную длину (до 60 символов).
    $title_prompt = "Based on the following content snippet for a '$format' article in '$language_full_name': \"$content_snippet\", generate a concise and highly engaging SEO title. The title must:
- Begin with either a special symbol (e.g., 'ᐈ') or an emoji (e.g., '🔥', '✅') chosen to best match the article's tone.
- Start with the primary keyword '$keyword' immediately.
- Include a clear call-to-action or engaging phrase.
- Use numbers if applicable and words that evoke sensory impressions.
- Be optimized for SEO and not exceed 60 characters.
Optionally, include '$site_name' at the end for branding.";
    
    // Новый промпт для SEO DESCRIPTION:
    // Требуется сформировать описание до 160 символов, которое точно отражает содержание, использует ключевое слово в начале,
    // содержит эмодзи или спецсимволы для привлечения внимания и подталкивает к действию.
    $description_prompt = "Given the same content snippet for a '$format' article in '$language_full_name': \"$content_snippet\", generate an SEO-optimized meta description. Requirements:
- Maximum 160 characters.
- Must start with the primary keyword '$keyword' or an appropriate symbol/emoji that catches attention.
- Include a call-to-action and relevant numbers if applicable.
- Clearly summarize the main points of the article.
- Incorporate '$site_name' for brand consistency.
Output the description in the same language as the content.";
    
    // Prepare headers for both requests
    $headers = [
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type'  => 'application/json',
    ];

    // Generate SEO Title
    $body = json_encode([
        'model'    => $text_model,
        'messages' => [['role' => 'user', 'content' => $title_prompt]],
    ]);
    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => $headers,
        'body'    => $body,
        'timeout' => 1000,
    ]);
    $seo_title = '';
    if (!is_wp_error($response)) {
        $result = json_decode(wp_remote_retrieve_body($response), true);
        $seo_title = $result['choices'][0]['message']['content'] ?? '';
    }
    $title_input_tokens = str_word_count($title_prompt);
    $title_output_tokens = str_word_count($seo_title);
    $seo_title = trim($seo_title, '"');

    // Generate SEO Description
    $body = json_encode([
        'model'    => $text_model,
        'messages' => [['role' => 'user', 'content' => $description_prompt]],
    ]);
    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => $headers,
        'body'    => $body,
        'timeout' => 1000,
    ]);
    $seo_description = '';
    if (!is_wp_error($response)) {
        $result = json_decode(wp_remote_retrieve_body($response), true);
        $seo_description = $result['choices'][0]['message']['content'] ?? '';
    }
    $desc_input_tokens = str_word_count($description_prompt);
    $desc_output_tokens = str_word_count($seo_description);
    $seo_description = trim($seo_description, '"');

    return [$seo_title, $seo_description, $title_input_tokens, $title_output_tokens, $desc_input_tokens, $desc_output_tokens];
}

function refine_seo_title_openai($seo_title, $keyword, $api_key, $text_model) {
    $prompt = "The current SEO title is: '$seo_title'. It does not prominently feature the primary keyword '$keyword' at the beginning or use engaging elements. Please refine the title so that it:
- Starts with '$keyword' (or includes an attention-grabbing symbol/emoji immediately before '$keyword'),
- Contains a clear call-to-action,
- Uses numbers and vivid, sensory language where appropriate,
- Is optimized for SEO with a maximum length of 60 characters.
Output only the refined title.";
    $headers = [
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type'  => 'application/json',
    ];
    $body = json_encode([
        'model'    => $text_model,
        'messages' => [['role' => 'user', 'content' => $prompt]],
    ]);
    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => $headers,
        'body'    => $body,
        'timeout' => 1000,
    ]);
    $refined_title = $seo_title;
    if (!is_wp_error($response)) {
        $result = json_decode(wp_remote_retrieve_body($response), true);
        $refined_title = $result['choices'][0]['message']['content'] ?? $seo_title;
    }
    $input_tokens = str_word_count($prompt);
    $output_tokens = str_word_count($refined_title);
    $refined_title = trim($refined_title, '"');
    return [$refined_title, $input_tokens, $output_tokens];
}

function refine_seo_description_openai($seo_description, $keyword, $api_key, $text_model) {
    $prompt = "The current SEO description is: '$seo_description'. It does not start with the primary keyword '$keyword' or include an engaging call-to-action. Please refine and enhance it so that it:
- Starts with '$keyword' (or with a captivating emoji/symbol preceding it),
- Contains a clear call-to-action,
- Uses numbers if relevant,
- Is within 160 characters,
- Is optimized for SEO.
Output only the refined description.";
    $headers = [
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type'  => 'application/json',
    ];
    $body = json_encode([
        'model'    => $text_model,
        'messages' => [['role' => 'user', 'content' => $prompt]],
    ]);
    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => $headers,
        'body'    => $body,
        'timeout' => 1000,
    ]);
    $refined_description = $seo_description;
    if (!is_wp_error($response)) {
        $result = json_decode(wp_remote_retrieve_body($response), true);
        $refined_description = $result['choices'][0]['message']['content'] ?? $seo_description;
    }
    $input_tokens = str_word_count($prompt);
    $output_tokens = str_word_count($refined_description);
    $refined_description = trim($refined_description, '"');
    return [$refined_description, $input_tokens, $output_tokens];
}
