<?php

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

/**
 * Handle forgot password request
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function content_craft_ai_handle_forgot_password($request)
{
  // Get request parameters - support both JSON and form data
  $params = $request->get_json_params();
  if (empty($params)) {
    $params = $request->get_params();
  }

  $email = isset($params['email']) ? sanitize_email($params['email']) : '';

  // Validate required fields
  if (empty($email)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Email is required.'
      ),
      400
    );
  }

  try {
    // Forward the forgot password request to the external API
    $response = wp_remote_post(CONTENT_CRAFT_AI_EXTERNAL_API . '/auth/forgot-password', array(
      'headers' => array(
        'Content-Type' => 'application/json',
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
      ),
      'body' => json_encode(array(
        'email' => $email
      )),
      'timeout' => 120
    ));

    if (is_wp_error($response)) {
      throw new Exception($response->get_error_message());
    }

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

    // Return the response as is
    return new WP_REST_Response(
      $body,
      $status_code
    );
  } catch (Exception $e) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => $e->getMessage()
      ),
      500
    );
  }
}
