<?php

/**
 * Content Craft AI - Edit Scheduled Article API Handler
 */

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

/**
 * Handle request to get scheduled article details
 * 
 * @param WP_REST_Request $request The REST API request.
 * @return WP_REST_Response The REST API response.
 */
function content_craft_ai_edit_scheduled_article($request)
{
  // Get request method to determine if this is a GET or POST request
  $method = $request->get_method();

  if ($method === 'GET' || $method === 'POST' && !$request->get_param('parameters')) {
    // Get details for a scheduled article
    $queue_id = $request->get_param('queueId');

    if (empty($queue_id)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Queue ID is required'
      ], 400);
    }

    // Get article status controller
    $article_status_controller = new ContentCraftAI_ArticleStatusController();

    // Get the scheduled article
    $generation = $article_status_controller->get_generation_by_queue_id($queue_id);

    if (!$generation) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Scheduled article not found'
      ], 404);
    }

    // Ensure it's a scheduled article
    if ($generation['status'] !== 'scheduled') {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Only scheduled articles can be edited'
      ], 400);
    }

    // Return the article details
    return new WP_REST_Response([
      'success' => true,
      'data' => $generation
    ], 200);
  } else {
    // Update a scheduled article
    $queue_id = $request->get_param('queueId');
    $parameters = $request->get_param('parameters');

    if (empty($queue_id)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Queue ID is required'
      ], 400);
    }

    if (empty($parameters)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Parameters are required'
      ], 400);
    }

    // Decode parameters if they are sent as a JSON string
    if (is_string($parameters)) {
      $parameters = json_decode($parameters, true);

      if (json_last_error() !== JSON_ERROR_NONE) {
        return new WP_REST_Response([
          'success' => false,
          'message' => 'Invalid parameters format'
        ], 400);
      }
    }

    // Get article status controller
    $article_status_controller = new ContentCraftAI_ArticleStatusController();

    // Get the scheduled article
    $generation = $article_status_controller->get_generation_by_queue_id($queue_id);

    if (!$generation) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Scheduled article not found'
      ], 404);
    }

    // Ensure it's a scheduled article
    if ($generation['status'] !== 'scheduled') {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Only scheduled articles can be edited'
      ], 400);
    }

    // Get current parameters and merge with new ones
    $current_params = !empty($generation['parameters']) ? $generation['parameters'] : [];

    // Always preserve these original scheduled article fields
    $preserved_fields = [
      'scheduleDateTime',
      'scheduled_time',
      'original_timezone',
      'is_scheduled'
    ];

    // Copy preserved fields before merging
    $preserved_values = [];
    foreach ($preserved_fields as $field) {
      if (isset($current_params[$field])) {
        $preserved_values[$field] = $current_params[$field];
      }
    }

    // Merge parameters, but ensure new params don't overwrite scheduled time
    $updated_params = array_merge($current_params, $parameters);

    // Restore preserved values
    foreach ($preserved_values as $field => $value) {
      $updated_params[$field] = $value;
    }

    // Update the article parameters
    $result = $article_status_controller->update_generation_parameters($queue_id, $updated_params);

    if ($result) {
      return new WP_REST_Response([
        'success' => true,
        'message' => 'Scheduled article updated successfully',
        'data' => [
          'queue_id' => $queue_id,
          'updated_params' => $updated_params
        ]
      ], 200);
    } else {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Failed to update scheduled article'
      ], 500);
    }
  }
}
