<?php
/**
 * EONSR AEO Agent - REST API Synchronization & Post Creation Logic
 *
 * Handles creation of scheduled posts via REST API, including smart media injection,
 * license syncing, and content formatting fixes (DOMDocument).
 *
 * @package EONSR_AEO_Agent
 */

if (!defined('ABSPATH')) {
    exit;
}

/* ==========================================================================
   SECTION 1: ROUTE REGISTRATION
   ========================================================================== */

add_action('rest_api_init', function () {
    // Route: Create Scheduled Post
    register_rest_route('eonsr-aeo-agent/v1', '/scheduled-post/create', [
        'methods'             => 'POST',
        'callback'            => 'eonsr_aeo_agent_create_scheduled_post_callback',
        'permission_callback' => '__return_true'
    ]);

    // Route: Get Polylang Languages
    register_rest_route('eonsr-aeo-agent/v1', '/languages', [
        'methods'             => 'GET',
        'callback'            => 'eonsr_aeo_agent_get_languages_callback',
        'permission_callback' => '__return_true'
    ]);

    // Route: Sync License
    register_rest_route('eonsr-aeo-agent/v1', '/sync-license', [
        'methods'             => 'POST',
        'callback'            => 'eonsr_aeo_agent_sync_license_callback',
        'permission_callback' => '__return_true',
    ]);
});

/* ==========================================================================
   SECTION 2: LICENSE & LANGUAGE CALLBACKS
   ========================================================================== */

/**
 * Validates and syncs the license key with the central server.
 *
 * @param WP_REST_Request $request
 * @return WP_REST_Response
 */
function eonsr_aeo_agent_sync_license_callback($request)
{
    $params = $request->get_json_params();

    if (!isset($params['key']) || !isset($params['domain'])) {
        return new WP_REST_Response(['success' => false], 400);
    }

    $license_key = sanitize_text_field($params['key']);
    // Updated Constant
    $api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/license/validate';

    $response = wp_remote_post($api_url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body'    => json_encode(['key' => $license_key, 'domain' => site_url()]),
        'timeout' => 15
    ]);

    if (is_wp_error($response)) {
        return new WP_REST_Response(['success' => false], 500);
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if (!isset($data['valid']) || $data['valid'] !== true) {
        return new WP_REST_Response(['success' => false], 400);
    }

    // Updated Option Names
    update_option('eonsr_aeo_agent_license_key', $license_key);
    update_option('eonsr_aeo_agent_license_status', 'activated');

    return new WP_REST_Response(['success' => true], 200);
}

/**
 * Retrieves the list of languages from Polylang.
 *
 * @return WP_REST_Response
 */
function eonsr_aeo_agent_get_languages_callback()
{
    if (function_exists('pll_languages_list')) {
        return new WP_REST_Response(['success' => true, 'languages' => pll_languages_list()], 200);
    }
    return new WP_REST_Response(['success' => true, 'languages' => []], 200);
}

/* ==========================================================================
   SECTION 3: CONTENT FILTERS
   ========================================================================== */

/**
 * Disable wpautop for posts with custom AEO styling.
 */
add_filter('the_content', 'eonsr_aeo_agent_disable_wpautop_for_styled_posts', 1);

function eonsr_aeo_agent_disable_wpautop_for_styled_posts($content)
{
    // Updated Meta Key
    if (is_singular('post') && get_post_meta(get_the_ID(), '_eonsr_aeo_has_custom_style', true) === 'yes') {
        remove_filter('the_content', 'wpautop');
        remove_filter('the_content', 'wptexturize');
    }
    return $content;
}

/**
 * Decode HTML entities before saving to database to preserve structure.
 */
add_filter('content_save_pre', 'eonsr_aeo_agent_preserve_raw_html', 1);

function eonsr_aeo_agent_preserve_raw_html($content)
{
    if (strpos($content, 'gemini-article-content') !== false) {
        $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }
    return $content;
}

/* ==========================================================================
   SECTION 4: MAIN POST CREATION CALLBACK
   ========================================================================== */

/**
 * Main Callback: Create Scheduled Post.
 *
 * @param WP_REST_Request $request
 * @return WP_REST_Response
 */
function eonsr_aeo_agent_create_scheduled_post_callback($request)
{
    // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Required for long-running post generation with AI content
    if (function_exists('set_time_limit')) set_time_limit(600);
    // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Required for AI content processing with large media files
    if (function_exists('ini_set')) ini_set('memory_limit', '512M');

    try {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- REST API request tracking for debugging
        error_log("[EONSR AEO REST] 🔥 Received Post Request (DOM Document Fix)");

        $params = $request->get_json_params();
        $result = eonsr_aeo_agent_handle_post_creation_logic($params);

        if (is_wp_error($result)) {
            throw new Exception($result->get_error_message());
        }

        return new WP_REST_Response([
            'success' => true,
            'message' => 'Post created successfully',
            'data'    => $result
        ], 200);

    } catch (Exception $e) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Critical error logging for post creation failures
        error_log("[EONSR AEO REST] ❌ Fatal Error: " . $e->getMessage());
        return new WP_REST_Response(['success' => false, 'message' => $e->getMessage()], 500);
    }
}

/**
 * Core Logic: Handles post data preparation, insertion, meta saving, and media logic.
 *
 * @param array $data Input data from API.
 * @return array|WP_Error
 */
function eonsr_aeo_agent_handle_post_creation_logic($data)
{
    // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Required for AI content generation timeout handling
    if (function_exists('set_time_limit')) set_time_limit(600);

    try {
        // 1. Extract Data
        $job_id         = $data['jobId'] ?? '';
        $content        = $data['content'] ?? '';
        $metadata       = $data['metadata'] ?? [];
        $image_prompts  = $data['imagePrompts'] ?? [];
        $summaries      = $data['summaries'] ?? [];
        $usage          = $data['usage'] ?? [];
        $params         = $data['params'] ?? [];
        $scheduled_time = $data['scheduledTime'] ?? '';

        $language       = $data['language'] ?? 'vi';
        $is_translation = $data['isTranslation'] ?? false;
        $source_post_id = $data['sourcePostId'] ?? null;

        // Media IDs (Reuse for translations)
        $featured_image_id   = $data['featuredImageId'] ?? null;
        $in_content_image_id = $data['inContentImageId'] ?? null;

        $skip_wp_translation = $data['skip_wp_translation'] ?? false;

        if (empty($content) || empty($metadata)) {
            return new WP_Error('missing_data', 'Missing content or metadata');
        }

        // 2. Process Time & Status
        $wp_timezone = wp_timezone();
        if (!empty($scheduled_time)) {
            $scheduled_datetime = new DateTime($scheduled_time, new DateTimeZone('UTC'));
            $scheduled_datetime->setTimezone($wp_timezone);
        } else {
            $scheduled_datetime = new DateTime('now', $wp_timezone);
        }

        $now = new DateTime('now', $wp_timezone);
        $diff = $scheduled_datetime->getTimestamp() - $now->getTimestamp();
        
        // Publish immediately if difference is small
        $final_status = ($diff <= 120) ? 'publish' : 'future';
        if ($final_status === 'publish') {
            $scheduled_datetime = $now;
        }

        // 3. Prepare & Insert Post
        $post_data = eonsr_aeo_agent_create_scheduled_post_data($content, $metadata, $final_status, $scheduled_datetime);

        if (!function_exists('post_exists')) {
            require_once(ABSPATH . 'wp-admin/includes/post.php');
        }

        // Temporarily disable filters to preserve raw HTML structure
        remove_filter('content_save_pre', 'wp_filter_post_kses');
        kses_remove_filters();
        
        $post_id = wp_insert_post($post_data, true);
        
        kses_init_filters(); // Re-enable filters

        if (is_wp_error($post_id)) {
            return $post_id;
        }

        // 4. Update Metadata (Updated Keys)
        update_post_meta($post_id, '_eonsr_aeo_has_custom_style', 'yes');
        update_post_meta($post_id, '_eonsr_aeo_job_id', $job_id);
        update_post_meta($post_id, '_eonsr_aeo_post_language', $language);

        if ($skip_wp_translation) {
            update_post_meta($post_id, '_eonsr_aeo_skip_wp_translation', 'yes');
        }
        if ($is_translation && $source_post_id) {
            update_post_meta($post_id, '_eonsr_aeo_translation_source_id', $source_post_id);
        }

        eonsr_aeo_agent_save_post_metadata($post_id, $metadata, $summaries, $usage, $params);

        // 5. Handle Media Logic
        $final_feat_id = null;
        $final_cont_id = null;
        $featured_image_url = null;
        $in_content_image_url = null;

        if ($is_translation) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Translation mode tracking for media handling
            error_log("[EONSR AEO REST] 🔄 Translation Mode: Setting Featured Image only (Injection disabled)...");

            // A. Featured Image (Reuse ID)
            if ($featured_image_id) {
                set_post_thumbnail($post_id, $featured_image_id);
                $final_feat_id = $featured_image_id;
                $featured_image_url = wp_get_attachment_url($featured_image_id);
            }

            // B. In-Content Image: Logic injected via DOMDocument is currently DISABLED per logic requirements.
            // if ($in_content_image_id) { ... }

        } else {
            // Original Post Mode: Generate New Images
            if (!empty($image_prompts['featured']) && function_exists('eonsr_aeo_agent_generate_and_attach_images')) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Image generation process tracking
                error_log("[EONSR AEO REST] 🖼️ Generating NEW images for original post...");
                
                eonsr_aeo_agent_generate_and_attach_images(
                    $post_id, 
                    $image_prompts['featured'], 
                    $image_prompts['in_content'] ?? ''
                );

                $final_feat_id = get_post_thumbnail_id($post_id);
                if ($final_feat_id) {
                    $featured_image_url = wp_get_attachment_url($final_feat_id);
                }

                $meta_cont = get_post_meta($post_id, '_eonsr_aeo_in_content_image_id', true);
                if ($meta_cont) {
                    $final_cont_id = (int)$meta_cont;
                    $in_content_image_url = wp_get_attachment_url($final_cont_id);
                }
            }
        }

        return [
            'postId'            => $post_id,
            'postUrl'           => get_permalink($post_id),
            'status'            => $final_status,
            'language'          => $language,
            'featuredImageId'   => $final_feat_id,
            'inContentImageId'  => $final_cont_id,
            'featuredImageUrl'  => $featured_image_url,
            'inContentImageUrl' => $in_content_image_url
        ];

    } catch (Exception $e) {
        return new WP_Error('logic_error', $e->getMessage());
    }
}

/* ==========================================================================
   SECTION 5: HELPER FUNCTIONS
   ========================================================================== */

/**
 * Prepares the post data array for insertion.
 */
function eonsr_aeo_agent_create_scheduled_post_data($content, $metadata, $status, $scheduled_datetime)
{
    $clean_content = eonsr_aeo_agent_deep_decode($content);
    $clean_content = str_replace(array('\\r\\n', '\\n', '\\r'), "\n", $clean_content);

    $title = $metadata['title'] ?? '';
    // If title missing, try extracting H1
    if (empty($title) && preg_match('/<h1[^>]*>(.*?)<\/h1>/is', $clean_content, $matches)) {
        $title = trim(wp_strip_all_tags($matches[0]));
    }

    // Handle CSS Scoping
    $style_block = '';
    if (preg_match('/<style[^>]*>(.*?)<\/style>/is', $clean_content, $style_matches)) {
        $css_inside = $style_matches[1];
        $css_inside = eonsr_aeo_agent_deep_decode($css_inside);
        
        if (strpos($css_inside, '.gemini-article-content') === false) {
            $scoped_css = eonsr_aeo_agent_scope_css($css_inside, '.gemini-article-content');
        } else {
            $scoped_css = $css_inside;
        }
        
        $style_block = "<style type='text/css'>" . preg_replace('/\s+/', ' ', $scoped_css) . "</style>";
        $clean_content = str_replace($style_matches[0], '', $clean_content);
    }

    // Remove H1 from body as it's set as post title
    if (preg_match('/(<h1[^>]*>.*?<\/h1>)/is', $clean_content, $h1_matches)) {
        $clean_content = str_replace($h1_matches[0], '', $clean_content);
    }

    // Wrap content in container class
    if (strpos($clean_content, 'gemini-article-content') === false) {
        $final_content = $style_block . '<div class="gemini-article-content">' . $clean_content . '</div>';
    } else {
        $final_content = $style_block . $clean_content;
    }

    return [
        'post_title'    => wp_strip_all_tags($title),
        'post_content'  => $final_content,
        'post_status'   => $status,
        'post_date'     => $scheduled_datetime->format('Y-m-d H:i:s'),
        'post_date_gmt' => get_gmt_from_date($scheduled_datetime->format('Y-m-d H:i:s')),
        'post_author'   => get_current_user_id() ?: 1,
        'post_type'     => 'post'
    ];
}

/**
 * Recursively decodes HTML entities.
 */
function eonsr_aeo_agent_deep_decode($text, $max = 5)
{
    $prev = '';
    $curr = $text;
    $i = 0;
    while ($prev !== $curr && $i < $max) {
        $prev = $curr;
        $curr = html_entity_decode($curr, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $i++;
    }
    return $curr;
}

if (!function_exists('eonsr_aeo_agent_scope_css')) {
    /**
     * Scopes CSS to a specific parent selector.
     */
    function eonsr_aeo_agent_scope_css($css, $scope)
    {
        return preg_replace('/([^\r\n,{}]+)(?=\{)/', $scope . ' $1', $css);
    }
}

/**
 * Saves SEO Meta, Tags, Summaries, and Usage Logs.
 */
function eonsr_aeo_agent_save_post_metadata($post_id, $metadata, $summaries, $usage, $params)
{
    global $wpdb;

    // SEO Meta (Keep original keys for Yoast/RankMath compatibility)
    if (!empty($metadata['meta_description'])) {
        update_post_meta($post_id, '_yoast_wpseo_metadesc', $metadata['meta_description']);
        update_post_meta($post_id, 'rank_math_description', $metadata['meta_description']);
    }
    if (!empty($metadata['focus_keyphrase'])) {
        update_post_meta($post_id, '_yoast_wpseo_focuskw', $metadata['focus_keyphrase']);
        update_post_meta($post_id, 'rank_math_focus_keyword', $metadata['focus_keyphrase']);
    }

    // Tags
    if (!empty($metadata['tags'])) {
        eonsr_aeo_agent_set_post_tags_safe($post_id, $metadata['tags']);
    }

    // Summaries (Updated Keys)
    if (!empty($summaries['paragraph'])) {
        update_post_meta($post_id, '_eonsr_aeo_summary_paragraph', $summaries['paragraph']);
        $bullets_json = json_encode($summaries['bullets'] ?? [], JSON_UNESCAPED_UNICODE);
        update_post_meta($post_id, '_eonsr_aeo_summary_bullets', wp_slash($bullets_json));
        update_post_meta($post_id, '_eonsr_aeo_has_summaries', 'yes');
    }

    // Usage Logging (Updated Table Name)
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table for usage logging, no WP equivalent
    $wpdb->insert($wpdb->prefix . 'eonsr_aeo_agent_cost_logs', [
        'post_id'              => $post_id,
        'generation_date'      => current_time('mysql'),
        'primary_term'         => $params['primary_term'] ?? '',
        'model_name'           => $params['model_name'] ?? 'gemini-2.5-flash',
        'search_queries'       => $usage['search_calls'] ?? 0,
        'youtube_queries'      => $usage['youtube_calls'] ?? 0,
        'gemini_usage_details' => wp_json_encode($usage['gemini'] ?? []),
    ]);
}

/**
 * Safely sets post tags (handles non-existing tags).
 */
function eonsr_aeo_agent_set_post_tags_safe($post_id, $tags_names)
{
    if (empty($tags_names) || !is_array($tags_names)) return;
    
    $tag_ids = array();
    
    foreach ($tags_names as $tag_name) {
        $tag_name = trim((string)$tag_name);
        if (empty($tag_name)) continue;
        
        $term = term_exists($tag_name, 'post_tag');
        
        if ($term === 0 || $term === null) {
            $new_term = wp_insert_term($tag_name, 'post_tag');
            if (!is_wp_error($new_term)) {
                $tag_ids[] = (int) $new_term['term_id'];
            }
        } else {
            $tag_ids[] = is_array($term) ? (int)$term['term_id'] : (int)$term;
        }
    }
    
    if (!empty($tag_ids)) {
        wp_set_object_terms($post_id, $tag_ids, 'post_tag', false);
    }
}