<?php

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

/**
 * Handle article status notifications to the external API
 * 
 * This file provides functions to notify the external API when articles are completed or fail
 */

// Include the API base class for common functionality
require_once __DIR__ . '/ApiBase.php';

/**
 * Notification controller for article generation status
 */
class ContentCraftAI_NotificationController extends ContentCraftAI_ApiBase
{
  /**
   * Instance of this class.
   *
   * @var ContentCraftAI_NotificationController
   */
  private static $instance = null;

  /**
   * Get an instance of this class.
   *
   * @return ContentCraftAI_NotificationController
   */
  public static function get_instance()
  {
    if (null === self::$instance) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  /**
   * Constructor
   */
  private function __construct()
  {
    parent::__construct();
  }

  /**
   * Get API queue ID from WordPress queue ID
   * 
   * @param string $queue_id The WordPress queue ID
   * @return string|null The API queue ID or null if not found
   */
  private function get_api_queue_id($queue_id)
  {
    // error_log("Content Craft AI: Attempting to find API queue ID for WordPress queue ID: {$queue_id}");

    // Get database manager
    $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
    $generation = $article_manager->get_generation_by_queue_id($queue_id);

    if ($generation && !empty($generation->parameters)) {
      $params = json_decode($generation->parameters, true);
      if ($params && !empty($params['apiQueueId'])) {
        // error_log("Content Craft AI: Found API queue ID {$params['apiQueueId']} in parameters for WordPress queue ID {$queue_id}");
        return $params['apiQueueId'];
      }
    }

    // If not found in parameters, check if the queue ID itself might be the API queue ID
    // This is the case for newer implementations where we directly use the API queue ID
    if (strlen($queue_id) >= 24 && strpos($queue_id, 'queue_') !== 0) {
      // error_log("Content Craft AI: Using the WordPress queue ID {$queue_id} as the API queue ID since it appears to be a valid API ID");
      return $queue_id;
    }

    // error_log("Content Craft AI: Cannot find API queue ID for {$queue_id} - no mapping found");
    return null;
  }

  /**
   * Notify the API that an article has been successfully completed
   * 
   * @param int $post_id The WordPress post ID
   * @param string $queue_id The generation queue ID
   * @return array|WP_Error The API response or WP_Error on failure
   */
  public function notify_article_completed($post_id, $queue_id)
  {
    // Check if email notifications are enabled for article completion
    $user_settings = get_option('content_craft_ai_user_settings', []);
    $notifications_enabled = isset($user_settings['emailNotifications']['articleCompletion'])
      ? $user_settings['emailNotifications']['articleCompletion']
      : false;

    if (!$notifications_enabled) {
      // error_log("Content Craft AI: Email notifications for article completion are disabled. Skipping notification.");
      return ['success' => true, 'message' => 'Notifications disabled, skipping'];
    }

    // error_log("Content Craft AI: Sending completion notification for post ID: {$post_id}, queue ID: {$queue_id}");

    // Get the API queue ID from the WordPress queue ID
    $api_queue_id = $this->get_api_queue_id($queue_id);
    if (!$api_queue_id) {
      // error_log("Content Craft AI: Cannot notify completion - API queue ID not found for {$queue_id}");
      return new WP_Error('missing_api_queue_id', "API queue ID not found for {$queue_id}");
    }

    // Get post details
    $post = get_post($post_id);
    if (!$post) {
      // error_log("Content Craft AI: Cannot notify completion - Post {$post_id} not found");
      return new WP_Error('post_not_found', "Post {$post_id} not found");
    }

    $post_url = get_permalink($post_id);
    // error_log("Content Craft AI: Post URL for notification: {$post_url}");

    // Request payload
    $payload = [
      'queueId' => $api_queue_id, // Use API queue ID, not WordPress queue ID
      'postId' => $post_id,
      'postUrl' => $post_url,
      'postStatus' => get_post_status($post_id),
      'title' => $post->post_title
    ];

    // Make API request
    $response = wp_remote_post(
      $this->api_url . '/articles/notify/completed',
      [
        'headers' => $this->get_common_headers(),
        'body' => json_encode($payload),
        'timeout' => 120
      ]
    );

    // Handle response
    if (is_wp_error($response)) {
      // error_log('Content Craft AI: Failed to send article completion notification - ' . $response->get_error_message());
      return $response;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    $status_code = wp_remote_retrieve_response_code($response);

    // error_log("Content Craft AI: Article completion notification sent with status {$status_code}: " . wp_json_encode($body));

    return $body;
  }

  /**
   * Notify the API that an article generation has failed
   * 
   * @param string $queue_id The generation queue ID
   * @param string $error_message Optional error message
   * @return array|WP_Error The API response or WP_Error on failure
   */
  public function notify_article_failed($queue_id, $error_message = null)
  {
    // Check if email notifications are enabled for article failure
    $user_settings = get_option('content_craft_ai_user_settings', []);
    $notifications_enabled = isset($user_settings['emailNotifications']['articleFailure'])
      ? $user_settings['emailNotifications']['articleFailure']
      : false;

    if (!$notifications_enabled) {
      // error_log("Content Craft AI: Email notifications for article failure are disabled. Skipping notification.");
      return ['success' => true, 'message' => 'Notifications disabled, skipping'];
    }

    // error_log("Content Craft AI: Sending failure notification for queue ID: {$queue_id}");

    // Get the API queue ID from the WordPress queue ID
    $api_queue_id = $this->get_api_queue_id($queue_id);
    if (!$api_queue_id) {
      // For failures, we'll use the WordPress queue ID if API queue ID is not found
      // error_log("Content Craft AI: API queue ID not found for {$queue_id}, using WordPress queue ID instead");
      $api_queue_id = $queue_id;
    }

    // Get article title from database
    $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
    $generation = $article_manager->get_generation_by_queue_id($queue_id);
    $title = $generation ? $generation->title : 'Unknown article';

    // Request payload
    $payload = [
      'queueId' => $api_queue_id,
      'title' => $title
    ];

    // Add error message if provided
    if ($error_message) {
      $payload['errorMessage'] = $error_message;
    }

    // Make API request
    $response = wp_remote_post(
      $this->api_url . '/articles/notify/failed',
      [
        'headers' => $this->get_common_headers(),
        'body' => json_encode($payload),
        'timeout' => 120
      ]
    );

    // Handle response
    if (is_wp_error($response)) {
      // error_log('Content Craft AI: Failed to send article failure notification - ' . $response->get_error_message());
      return $response;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    $status_code = wp_remote_retrieve_response_code($response);

    // error_log("Content Craft AI: Article failure notification sent with status {$status_code}: " . wp_json_encode($body));

    return $body;
  }
}

/**
 * Helper function to send article completion notification
 * 
 * @param int $post_id The WordPress post ID
 * @param string $queue_id The generation queue ID
 * @return array|WP_Error The API response or WP_Error on failure
 */
function content_craft_ai_notify_article_completed($post_id, $queue_id)
{
  $notification_controller = ContentCraftAI_NotificationController::get_instance();
  return $notification_controller->notify_article_completed($post_id, $queue_id);
}

/**
 * Helper function to send article failure notification
 * 
 * @param string $queue_id The generation queue ID
 * @param string $error_message Optional error message
 * @return array|WP_Error The API response or WP_Error on failure
 */
function content_craft_ai_notify_article_failed($queue_id, $error_message = null)
{
  $notification_controller = ContentCraftAI_NotificationController::get_instance();
  return $notification_controller->notify_article_failed($queue_id, $error_message);
}
