<?php

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

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

  $token = isset($params['token']) ? sanitize_text_field($params['token']) : '';
  $password = isset($params['password']) ? $params['password'] : '';

  // Validate required fields
  if (empty($token) || empty($password)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Token and password are required.'
      ),
      400
    );
  }

  try {
    // Forward the reset password request to the external API
    $response = wp_remote_post(CONTENT_CRAFT_AI_EXTERNAL_API . '/auth/reset-password', array(
      'headers' => array(
        'Content-Type' => 'application/json',
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
      ),
      'body' => json_encode(array(
        'token' => $token,
        'password' => $password
      )),
      '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);

    // If password reset was successful and we got a token, store it
    if ($status_code === 200 && isset($body['success']) && $body['success'] && isset($body['token']) && isset($body['user'])) {
      update_option('content_craft_ai_token', $body['token']);
    }

    // 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
    );
  }
}
