<?php

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

/**
 * Get available AI models from the API
 * 
 * @return WP_REST_Response Response with AI models data
 */
function content_craft_ai_get_models()
{
  // Check if API key exists
  $api_key = get_option('content_craft_ai_api_key');
  if (empty($api_key)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Authentication required',
      ),
      401
    );
  }

  // Make request to API
  $response = wp_remote_get(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/plan-features/models',
    array(
      'headers' => array(
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST),
        'Content-Type' => 'application/json',
      ),
      'timeout' => 120,
    )
  );

  // Check for error
  if (is_wp_error($response)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => $response->get_error_message(),
      ),
      500
    );
  }

  $body = wp_remote_retrieve_body($response);
  $status = wp_remote_retrieve_response_code($response);

  // Handle API errors
  if ($status !== 200) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Error fetching models',
        'data' => json_decode($body, true),
      ),
      $status
    );
  }

  // Parse API response data
  $api_response = json_decode($body, true);

  // Format models data for frontend
  $models_data = array();

  if (isset($api_response['data']) && isset($api_response['data']['allowedModels'])) {
    foreach ($api_response['data']['allowedModels'] as $model_id) {
      $models_data[] = array(
        'id' => $model_id,
        'name' => $model_id,
      );
    }
  }

  // Return success response
  return new WP_REST_Response(
    array(
      'success' => true,
      'data' => $models_data,
    ),
    200
  );
}

/**
 * Handle GET request for AI models
 * 
 * @return WP_REST_Response Response with AI models data
 */
function content_craft_ai_handle_get_models()
{
  return content_craft_ai_get_models();
}
