<?php

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

/**
 * Handle registration request
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function content_craft_ai_handle_register($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']) : '';
  $password = isset($params['password']) ? $params['password'] : '';
  $name = isset($params['name']) ? sanitize_text_field($params['name']) : '';
  $company = isset($params['company']) ? sanitize_text_field($params['company']) : '';

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

  try {
    // Forward the registration request to the external API
    $response = wp_remote_post(CONTENT_CRAFT_AI_EXTERNAL_API . '/auth/register', 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,
        'password' => $password,
        'name' => $name,
        'company' => $company
      )),
      '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);

    // Handle different response status codes
    if ($status_code !== 201 || !$body || isset($body['error']) || !$body['success']) {
      $message = $body['message'] ?? 'Registration failed';
      $error_code = isset($body['error']) ? $body['error'] : 'registration_error';

      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => $message,
          'error' => $error_code
        ),
        $status_code
      );
    }

    // Store token and API key in WordPress database
    if (isset($body['token']) && isset($body['user'])) {
      update_option('content_craft_ai_token', $body['token']);
      update_option('content_craft_ai_api_key', $body['apiKey'] ?? '');
    }

    return rest_ensure_response($body);
  } catch (Exception $e) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => $e->getMessage()
      ),
      500
    );
  }
}
