<?php
// app/controllers/article-generator/PostCreationManager.php

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

// Ensure dependent managers are available
if (!class_exists('ContentCraftAI_ArticleGenerationManager')) {
  require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/database/ArticleGenerationManager.php';
}

// Require helper files for post creation
require_once __DIR__ . '/postCreation/image-handler.php';
require_once __DIR__ . '/postCreation/seo-meta-handler.php';
require_once __DIR__ . '/postCreation/faq-handler.php';
require_once __DIR__ . '/postCreation/smart-link-handler.php';
require_once __DIR__ . '/postCreation/internal-link-handler.php';

/**
 * Manages the creation of WordPress posts from completed article generation data.
 */
class ContentCraftAI_PostCreationManager
{
  private static $instance = null;

  public static function get_instance()
  {
    if (self::$instance === null) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  private function __construct()
  {
    // Private constructor
  }

  /**
   * Creates a WordPress post from the API response data.
   *
   * @param string $queue_id The local queue ID of the generation.
   * @param array $api_response_data The full API response data.
   * @return int|false Post ID if successful, false if failed.
   */
  public function create_post_from_content($queue_id, $api_response_data)
  {
    // Add a very specific log here to ensure this method is indeed being called with the data we think.
    // error_log('Content Craft AI: PostCreationManager entry point. Queue ID: ' . $queue_id . '. Data received: ' . print_r($api_response_data, true));

    // Validate essential data from API response
    // if (!isset($api_response_data['content']['fullContent']) || empty($api_response_data['content']['fullContent'])) { // Original check

    // Let's break down the check to be absolutely sure
    if (!isset($api_response_data['content'])) {
      // error_log('Content Craft AI: PostCreationManager - API response data is missing the [content] key for queue ID: ' . $queue_id);
      // error_log('Content Craft AI: PostCreationManager - Full data dump: ' . print_r($api_response_data, true));
      return false;
    }
    if (!isset($api_response_data['content']['fullContent'])) {
      // error_log('Content Craft AI: PostCreationManager - API response data[\'content\'] is missing the [fullContent] key for queue ID: ' . $queue_id);
      // error_log('Content Craft AI: PostCreationManager - Dump of data[\'content\']: ' . print_r($api_response_data['content'], true));
      return false;
    }
    if (empty($api_response_data['content']['fullContent'])) {
      // error_log('Content Craft AI: PostCreationManager - API response data[\'content\'][\'fullContent\'] is EMPTY for queue ID: ' . $queue_id);
      // error_log('Content Craft AI: PostCreationManager - Value of fullContent: ' . $api_response_data['content']['fullContent']);
      return false;
    }

    // error_log('Content Craft AI: PostCreationManager - Creating post from content');
    global $wpdb;
    $article_generation_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
    $generation = $article_generation_manager->get_generation_by_queue_id($queue_id);

    if (!$generation || !$generation->parameters) {
      // error_log("Content Craft AI: PostCreationManager - Generation data not found for queue ID: {$queue_id}");
      return false;
    }

    $params = json_decode($generation->parameters, true);
    if (!$params) {
      // error_log("Content Craft AI: PostCreationManager - Could not decode parameters for queue ID: {$queue_id}");
      return false;
    }

    $post_title = $params['title'] ?? 'Untitled Article';
    $user_id = $generation->user_id ?? 1; // Default to admin user ID if missing
    $category_id = $params['category'] ?? null;
    $post_status = $params['postStatus'] ?? 'draft';
    $focus_keyword = $params['focusKeyword'] ?? '';
    $tags = $api_response_data['tags'] ?? [];

    // Get language from API response, then from article parameters, then from user settings, then default to 'en'
    $user_settings = get_option('content_craft_ai_user_settings', []);
    $user_default_language = $user_settings['defaultLanguage'] ?? 'en';
    $article_language = strtolower($api_response_data['language'] ?? $params['language'] ?? $user_default_language);

    $article_full_content = $api_response_data['content']['fullContent'] ?? '';
    if (empty($article_full_content)) {
      // error_log("Content Craft AI: PostCreationManager - API response missing fullContent for queue ID: {$queue_id}");
      $article_generation_manager->update_generation_status($queue_id, 'failed');
      // Store error in parameters
      $params['error_message'] = 'API response missing fullContent.';
      $wpdb->update(
        $wpdb->prefix . 'content_craft_ai_generations',
        ['parameters' => json_encode($params)],
        ['queue_id' => $queue_id],
        ['%s'],
        ['%s']
      );

      // Send failure notification
      if (function_exists('content_craft_ai_notify_article_failed')) {
        content_craft_ai_notify_article_failed($queue_id, 'API response missing content');
      }

      return false;
    }

    // Handle content images (ported from old controller)
    $content_images_html = '';
    if (!empty($api_response_data['imageData']['contentImages'])) {
      foreach ($api_response_data['imageData']['contentImages'] as $image) {
        if (isset($image['url'])) {
          $attachment_id = content_craft_ai_download_and_attach_image($image['url'], $post_title, $user_id);
          if ($attachment_id) {
            $content_images_html .= wp_get_attachment_image($attachment_id, 'full', false, [
              'alt' => $post_title,
              'title' => $post_title
            ]) . "\n\n";
          }
        }
      }
    }

    // Insert content images (ported logic)
    $final_post_content = $article_full_content;
    if (!empty($content_images_html)) {
      preg_match_all('/<h[2-6][^>]*>.*?<\/h[2-6]>/is', $final_post_content, $headings, PREG_OFFSET_CAPTURE);
      if (count($headings[0]) > 1) {
        $target_heading_index = (count($headings[0]) > 2) ? 2 : 1;
        $insert_position = $headings[0][$target_heading_index][1];
        $final_post_content = substr($final_post_content, 0, $insert_position) .
          "\n\n" . $content_images_html . "\n\n" .
          substr($final_post_content, $insert_position);
      } else {
        $final_post_content = $content_images_html . $final_post_content;
      }
    }

    // Add Smart Links if they exist in the API response
    if (!empty($api_response_data['links'])) {
      $final_post_content = content_craft_ai_insert_smart_links(
        $final_post_content,
        $api_response_data['links'],
        $article_language
      );
    }

    // Add FAQ section if enabled and available
    $user_settings = get_option('content_craft_ai_user_settings', []);
    $include_faq = $user_settings['includeFAQ'] ?? false;

    if ($include_faq && !empty($api_response_data['faq']['items'])) {
      $faq_html = content_craft_ai_generate_faq_html($api_response_data['faq'], $article_language);
      if (!empty($faq_html)) {
        $final_post_content .= $faq_html; // Append FAQ to the main content
        // error_log("Content Craft AI: PostCreationManager - Appended FAQ section to article content.");
      }
    }

    $post_data = [
      'post_title'    => $post_title,
      'post_content'  => $final_post_content,
      'post_status'   => $post_status,
      'post_author'   => $user_id,
      'tags_input'    => $tags
    ];

    if ($category_id) {
      $post_data['post_category'] = [(int)$category_id];
    }

    $post_id = wp_insert_post($post_data, true); // Pass true to return WP_Error on failure

    if (is_wp_error($post_id)) {
      // error_log("Content Craft AI: PostCreationManager - Failed to create post for queue ID {$queue_id}: " . $post_id->get_error_message());
      $article_generation_manager->update_generation_status($queue_id, 'failed');
      $params['error_message'] = 'Failed to insert post: ' . $post_id->get_error_message();
      $wpdb->update(
        $wpdb->prefix . 'content_craft_ai_generations',
        ['parameters' => json_encode($params)],
        ['queue_id' => $queue_id],
        ['%s'],
        ['%s']
      );
      return false;
    }

    // Set featured image (ported from old controller)
    if (!empty($api_response_data['imageData']['featuredImage']['url'])) {
      $featured_image_id = content_craft_ai_download_and_attach_image($api_response_data['imageData']['featuredImage']['url'], $post_title, $user_id);
      if ($featured_image_id) {
        set_post_thumbnail($post_id, $featured_image_id);
      }
    }

    // Handle SEO metadata using the new helper function
    content_craft_ai_apply_seo_metadata($post_id, $final_post_content, $focus_keyword);

    // If post is published, refresh internal links (would need to be implemented similar to old version)
    if ($post_status === 'publish') {
      // Add a hook for future internal link refreshing functionality
      do_action('content_craft_ai_post_published', $post_id, $focus_keyword, $tags);
    }

    // Final success actions
    // error_log("Content Craft AI: PostCreationManager - Successfully created post #{$post_id} for queue ID: {$queue_id}");

    // Add post creation hook for extensions
    if (function_exists('do_action')) {
      do_action('content_craft_ai_post_created', $post_id, $queue_id, $api_response_data);
    }

    // Send success notification
    if (function_exists('content_craft_ai_notify_article_completed')) {
      content_craft_ai_notify_article_completed($post_id, $queue_id);
    }

    return $post_id;
  }

  /**
   * Prepare data for API request
   * 
   * @param array $params The article generation parameters
   * @return array Modified parameters with internal links data if enabled
   */
  public function prepare_api_data($params)
  {
    // Get internal links data if enabled
    $user_settings = get_option('content_craft_ai_user_settings', []);
    $smart_linking_enabled = $user_settings['smartLinkingEnabled'] ?? false;

    if ($smart_linking_enabled && !empty($params['title']) && function_exists('content_craft_ai_get_internal_links_for_api')) {
      $focus_keyword = $params['focusKeyword'] ?? '';
      $category_id = $params['category'] ?? null;

      // Find relevant internal links for this article
      $internal_links = content_craft_ai_get_internal_links_for_api($focus_keyword, $category_id);

      if (!empty($internal_links)) {
        $params['internalLinks'] = $internal_links;
      }
    }

    return $params;
  }
}
