<?php

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

/**
 * Get user subscription data from the API
 * 
 * @return WP_REST_Response Response with subscription data
 */
function content_craft_ai_get_subscription()
{
  // Add no-cache headers to prevent browser caching of subscription data
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  header('Cache-Control: post-check=0, pre-check=0', false);
  header('Pragma: no-cache');
  header('Expires: 0');

  // 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 with timestamp to prevent caching
  $response = wp_remote_get(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/user/subscription?_=' . time(),
    array(
      'headers' => array(
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST),
        'Content-Type' => 'application/json',
        'Cache-Control' => 'no-cache, no-store, must-revalidate',
        'Pragma' => 'no-cache',
      ),
      '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 subscription data',
        'data' => json_decode($body, true),
      ),
      $status
    );
  }

  // Create response with no-cache headers
  $api_response = json_decode($body, true);
  $response = new WP_REST_Response($api_response, 200);

  // Ensure no caching
  $response->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
  $response->header('Pragma', 'no-cache');
  $response->header('Expires', '0');

  return $response;
}
