<?php
// Protection from direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

define('LOG_FILE_SINGLE', 'single-post-generation.php');

// Получаем (или генерируем) UID из POST
$progress_uid = isset($_POST['progress_uid']) ? sanitize_text_field($_POST['progress_uid']) : uniqid();

// Готовим путь к файлу, в котором будем хранить маркеры прогресса
$GLOBALS['ai_content_wizard_progress_file'] = WP_CONTENT_DIR . '/uploads/ai_content_wizard_progress_' . $progress_uid . '.txt';

/**
 * Обновляет прогресс генерации (пишет текущий этап в файл).
 *
 * @param string $marker Маркер текущего этапа (keyword_generation, content_creation, ...).
 */
if ( ! function_exists( 'ai_content_wizard_update_progress_single' ) ) {
    function ai_content_wizard_update_progress_single( $marker ) {
        global $ai_content_wizard_progress_file;
        file_put_contents( $ai_content_wizard_progress_file, $marker );
    }
}

require_once 'generate-text.php';
require_once 'generate-image.php';
require_once 'seo-optimization.php';
require_once 'ai_content_wizard_slug.php';

/**
 * Generates a single post based on the provided parameters.
 */
function ai_content_wizard_generate_single_post( $category_id, $post_topic, $related_articles, $selected_language, $selected_post_status, $single_post_additional_request, $author = null ) {

    // Объявляем переменные как глобальные и задаем значения по умолчанию, если они отсутствуют
    global $api_key, $text_model, $image_model;
    $text_model = ai_content_wizard_get_setting( 'ai_content_wizard_text_model', 'gpt-4-turbo' );
    $image_model = ai_content_wizard_get_setting( 'ai_content_wizard_image_model', 'dall-e-2' );
    // Если возвращаемое значение null, принудительно приводим к пустой строке
    $text_model = trim( $text_model ?? '' );
    $image_model = trim( $image_model ?? '' );

    // Проверка существования категории
    if ( term_exists( $category_id, 'category' ) === null ) {
        return false;
    }

    $category = get_category( $category_id );
    if ( ! $category || is_wp_error( $category ) ) {
        error_log( 'Invalid category ID: ' . $category_id );
        return false;
    }

    ai_content_wizard_update_progress_single( 'keyword_generation' );

    // Генерация или получение ключевого слова
    $keyword = ai_content_wizard_get_or_generate_keyword( $post_topic, $category->name, $selected_language, $api_key, $text_model );

    // Получаем глобальные настройки (категорийные настройки не используются в Lite)
    $format         = ai_content_wizard_get_setting( 'ai_content_wizard_format', 'post' );
    $text_length    = ai_content_wizard_get_setting( 'ai_content_wizard_text_length', '500' );
    $site_type      = ai_content_wizard_get_setting( 'ai_content_wizard_site_type', 'store' );
    $writing_style  = ai_content_wizard_get_setting( 'ai_content_wizard_writing_style', 'formal' );
    $target_audience = ai_content_wizard_get_setting( 'ai_content_wizard_target_audience', 'general' );
    $custom_theme   = ai_content_wizard_get_setting( 'ai_content_wizard_custom_theme' );
    $additional_requests = ai_content_wizard_get_setting( 'ai_content_wizard_additional_requests' );
    $target_region  = ai_content_wizard_get_setting( 'ai_content_wizard_target_region' );

    // Если передан дополнительный запрос, добавляем его
    if ( ! empty( $single_post_additional_request ) ) {
        $additional_requests .= " " . $single_post_additional_request;
    }

    ai_content_wizard_update_progress_single( 'content_creation' );

    try {
        $attempt = 0;
        $max_attempts = 2; // Максимальное количество попыток
        $successful = false;
        $delay_between_attempts = 5; // Задержка между попытками в секундах

        while ( ! $successful && $attempt < $max_attempts ) {
            $result = ai_content_wizard_generate_text(
                $post_topic,
                $category->name,
                $selected_language,
                $keyword,
                $format,
                $text_length,
                $site_type,
                $writing_style,
                $target_audience,
                $custom_theme,
                $additional_requests,
                $single_post_additional_request,
                $target_region,
                $related_articles
            );

            $article_title   = $result['title']   ?? '';
            $article_content = $result['content'] ?? '';
            $input_tokens    = $result['input_tokens'] ?? 0;
            $output_tokens   = $result['output_tokens'] ?? 0;

            if ( ! empty( $article_title ) && ! empty( $article_content ) && strlen( strip_tags( $article_content ) ) >= 200 ) {
                $successful = true;
            } else {
                $attempt++;
                if ( $attempt < $max_attempts ) {
                    error_log( "AI Content Wizard: Attempt $attempt failed. Retrying after $delay_between_attempts seconds." );
                    sleep( $delay_between_attempts );
                }
            }
        }

        if ( ! $successful ) {
            error_log( "Не удалось сгенерировать текст после $max_attempts попыток." );
            ai_content_wizard_log_generation( array(
                'post_id'        => null,
                'type'           => 'Single',
                'category'       => $category->name,
                'generation_time'=> current_time( 'mysql' ),
                'publish_time'   => null,
                'title'          => null,
                'keyword'        => $keyword,
                'language'       => $selected_language,
                'text_model'     => $text_model,
                'image_model'    => $image_model,
                'image_cost'     => 0,
                'text_cost'      => 0,
                'total_cost'     => 0,
                'status'         => 'Text generation failed after maximum attempts'
            ) );
            return false;
        }
    } catch ( Exception $e ) {
        error_log( 'Ошибка при генерации текста: ' . $e->getMessage() );
        ai_content_wizard_log_generation( array(
            'post_id'        => null,
            'type'           => 'Single',
            'category'       => $category->name,
            'generation_time'=> current_time( 'mysql' ),
            'publish_time'   => null,
            'title'          => null,
            'keyword'        => $keyword,
            'language'       => $selected_language,
            'text_model'     => $text_model,
            'image_model'    => $image_model,
            'image_cost'     => 0,
            'text_cost'      => 0,
            'total_cost'     => 0,
            'status'         => 'Error during text generation: ' . $e->getMessage()
        ) );
        return false;
    }

    if ( empty( $article_title ) || empty( $article_content ) || stripos( $article_title, 'no title generated' ) !== false ) {
        error_log( 'Generated content is empty or has no title generated' );
        ai_content_wizard_log_generation( array(
            'post_id'        => null,
            'type'           => 'Single',
            'category'       => $category->name,
            'generation_time'=> current_time( 'mysql' ),
            'publish_time'   => null,
            'title'          => null,
            'keyword'        => $keyword,
            'language'       => $selected_language,
            'text_model'     => $text_model,
            'image_model'    => $image_model,
            'image_cost'     => 0,
            'text_cost'      => 0,
            'total_cost'     => 0,
            'status'         => 'Generated content is empty or has no title generated'
        ) );
        return false;
    }

    // В Lite-версии не генерируются дополнительные изображения
    $image_cost = 0;

    // Подготавливаем данные для создания поста
    $post_data = array(
        'post_title'    => wp_strip_all_tags( $article_title ),
        'post_content'  => $article_content,
        'post_status'   => $selected_post_status,
        'post_author'   => ! empty( $author ) ? intval( $author ) : get_current_user_id(),
        'post_category' => array( $category_id )
    );

    $post_id = wp_insert_post( $post_data );
    if ( is_wp_error( $post_id ) ) {
        error_log( 'Failed to create post: ' . print_r( $post_id, true ) );
        ai_content_wizard_log_generation( array(
            'post_id'        => null,
            'type'           => 'Single',
            'category'       => $category->name,
            'generation_time'=> current_time( 'mysql' ),
            'publish_time'   => null,
            'title'          => $article_title,
            'keyword'        => $keyword,
            'language'       => $selected_language,
            'text_model'     => $text_model,
            'image_model'    => $image_model,
            'image_cost'     => $image_cost,
            'text_cost'      => 0,
            'total_cost'     => 0,
            'status'         => 'Failed to create post'
        ) );
        return false;
    }

    try {
        // Генерация слага на основе ключевой фразы
        $slug = generate_slug_from_keyword( $keyword );
        wp_update_post( array(
            'ID'        => $post_id,
            'post_name' => $slug,
        ) );
    } catch ( Exception $e ) {
        error_log( 'Ошибка при генерации слага или обновлении поста: ' . $e->getMessage() );
    }

    ai_content_wizard_update_progress_single( 'featured_image' );

    try {
        // Генерация миниатюры
        $attempt = 0;
        $max_attempts = 2;
        $successful = false;
        $delay_between_attempts = 5;

        while ( ! $successful && $attempt < $max_attempts ) {
            $image_data = ai_content_wizard_generate_image(
                $article_title,
                $article_content,
                $image_model,
                ai_content_wizard_get_setting( 'ai_content_wizard_image_size', '1792x1024' ),
                ai_content_wizard_get_setting( 'ai_content_wizard_image_quality', 'standard' ),
                $keyword,
                $category_id
            );

            if ( $image_data && ! empty( $image_data['url'] ) ) {
                $thumbnail_cost = isset( $image_data['cost'] ) ? (float) $image_data['cost'] : 0;
                $image_cost += $thumbnail_cost;

                $file_name = isset( $image_data['file_name'] ) ? $image_data['file_name'] : 'default_image_name';
                $attachment_id = ai_content_wizard_process_image( $image_data['url'], $file_name );

                if ( $attachment_id ) {
                    $alt_text = ai_content_wizard_generate_image_alt_text( $post_id, $keyword, $selected_language )['alt_text'];
                    update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text );
                    if ( ! set_post_thumbnail( $post_id, $attachment_id ) ) {
                        error_log( "Failed to set thumbnail for post $post_id with attachment $attachment_id" );
                    } else {
                        $successful = true;
                    }
                } else {
                    error_log( "Failed to process image for post $post_id" );
                }
            } else {
                error_log( "No image URL received in the image data." );
            }

            $attempt++;
            if ( ! $successful && $attempt < $max_attempts ) {
                error_log( "AI Content Wizard: Retrying image generation for post $post_id: Attempt $attempt" );
                sleep( $delay_between_attempts );
            }
        }

        if ( ! $successful ) {
            error_log( "Failed to set a thumbnail after $max_attempts attempts for post $post_id." );
        }
    } catch ( Exception $e ) {
        error_log( 'Error during image generation or setting for post: ' . $e->getMessage() );
    }

    // Расчет стоимости генерации текста
    $text_cost = calculate_text_generation_cost( $text_model, $input_tokens, $output_tokens ) ?? 0;

    ai_content_wizard_update_progress_single( 'seo_optimization' );

    try {
        // Генерация SEO элементов и расчет их стоимости
        $seo_result = ai_content_wizard_generate_seo_elements( $post_id, $keyword, $api_key, $text_model, $selected_language );
        $seo_success = isset( $seo_result[0] ) ? $seo_result[0] : false;
        $seo_input_tokens = isset( $seo_result[1] ) ? $seo_result[1] : 0;
        $seo_output_tokens = isset( $seo_result[2] ) ? $seo_result[2] : 0;
        $seo_cost = calculate_text_generation_cost( $text_model, $seo_input_tokens, $seo_output_tokens ) ?: 0;
    } catch ( Exception $e ) {
        error_log( 'Ошибка при генерации SEO элементов: ' . $e->getMessage() );
        $seo_cost = 0;
        $seo_success = false;
    }

    ai_content_wizard_update_progress_single( 'alt_texts' );

    try {
        // Генерация и расчет стоимости ALT текста
        $alt_text_result = ai_content_wizard_generate_image_alt_text( $post_id, $keyword, $selected_language );
        $alt_cost = isset( $alt_text_result['cost'] ) ? $alt_text_result['cost'] : 0;
    } catch ( Exception $e ) {
        error_log( 'Ошибка при генерации ALT текста: ' . $e->getMessage() );
        $alt_cost = 0;
    }

    $total_cost = $text_cost + $seo_cost + $image_cost + $alt_cost;

    $publish_date = current_time( 'mysql' );

    $log_data = array(
        'post_id'        => $post_id,
        'type'           => 'Single',
        'category'       => $category->name,
        'generation_time'=> current_time( 'mysql' ),
        'publish_time'   => $publish_date,
        'title'          => $article_title,
        'keyword'        => $keyword,
        'language'       => $selected_language,
        'text_model'     => $text_model,
        'image_model'    => $image_model,
        'image_cost'     => $image_cost,
        'text_cost'      => $text_cost,
        'total_cost'     => $total_cost,
        'status'         => 'Success'
    );

    try {
        ai_content_wizard_log_generation( $log_data );
    } catch ( Exception $e ) {
        error_log( 'Ошибка при логировании данных: ' . $e->getMessage() );
    }

    // В Lite-версии отправка в Telegram не осуществляется

    ai_content_wizard_update_progress_single( 'done' );

    // Пауза для фронтенда
    sleep( 3 );

    if ( file_exists( $GLOBALS['ai_content_wizard_progress_file'] ) ) {
        unlink( $GLOBALS['ai_content_wizard_progress_file'] );
    }

    return $post_id;
}

/**
 * Handles AJAX request for generating a single post.
 */
function ai_content_wizard_ajax_generate_single_post() {
    //check_ajax_referer('ai_content_wizard_nonce', 'security');

    $category_id = isset( $_POST['category'] ) ? intval( $_POST['category'] ) : 0;
    $post_topic = isset( $_POST['post_topic'] ) ? sanitize_text_field( $_POST['post_topic'] ) : '';

    if ( empty( $_POST['related_articles'] ) ) {
        $related_articles = get_related_articles_from_category( $category_id, 0 );
    } else {
        $related_articles = json_decode( stripslashes( $_POST['related_articles'] ), true );
        if ( ! is_array( $related_articles ) ) {
            $related_articles = [];
        }
    }

    $author = isset( $_POST['author'] ) ? intval( $_POST['author'] ) : get_current_user_id();
    $selected_language = isset( $_POST['language_select'] ) ? sanitize_text_field( $_POST['language_select'] ) : 'en';
    $selected_post_status = isset( $_POST['single_post_status'] ) ? sanitize_text_field( $_POST['single_post_status'] ) : 'publish';
    $single_post_additional_request = isset( $_POST['single_post_additional_request'] ) ? sanitize_textarea_field( $_POST['single_post_additional_request'] ) : '';

    $post_id = ai_content_wizard_generate_single_post(
        $category_id,
        $post_topic,
        $related_articles,
        $selected_language,
        $selected_post_status,
        $single_post_additional_request,
        $author
    );

    if ( $post_id ) {
        $post_title = get_the_title( $post_id );
        if ( stripos( $post_title, 'no title generated' ) !== false ) {
            wp_delete_post( $post_id, true );
            wp_send_json_error( [ 'message' => 'Failed to create post due to invalid title' ] );
        } else {
            wp_send_json_success( [
                'post_id'    => $post_id,
                'post_url'   => get_permalink( $post_id ),
                'post_title' => $post_title
            ] );
        }
    } else {
        wp_send_json_error( [ 'message' => 'Failed to create post' ] );
    }
}
add_action( 'wp_ajax_generate_single_post', 'ai_content_wizard_ajax_generate_single_post' );


function ai_content_wizard_get_generation_progress() {
    $progress_uid = isset($_REQUEST['progress_uid']) ? sanitize_text_field($_REQUEST['progress_uid']) : '';
    if (empty($progress_uid)) {
        wp_send_json_error(array('message' => 'Progress UID not provided'));
        return;
    }
    $progress_file = WP_CONTENT_DIR . '/uploads/ai_content_wizard_progress_' . $progress_uid . '.txt';
    
    if (file_exists($progress_file)) {
        $marker = file_get_contents($progress_file);
        wp_send_json_success(array('marker' => $marker));
    } else {
        // Если файл не найден, предполагаем, что генерация завершена
        wp_send_json_success(array('marker' => 'done'));
    }
}


add_action('wp_ajax_get_generation_progress', 'ai_content_wizard_get_generation_progress');
add_action('wp_ajax_nopriv_get_generation_progress', 'ai_content_wizard_get_generation_progress');