<?php

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

/**
 * Handle login request
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function content_craft_ai_handle_login($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'] : '';

    // Validate required fields
    if (empty($email) || empty($password)) {
        return new WP_Error(
            'missing_fields',
            'Email and password are required.',
            array('status' => 400)
        );
    }

    try {
        // Forward the login request to the external API
        $response = wp_remote_post(CONTENT_CRAFT_AI_EXTERNAL_API . '/auth/login', 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
            )),
            '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 ($status_code !== 200 || !$body || isset($body['error']) || !$body['success']) {
            throw new Exception($body['message'] ?? 'Invalid credentials');
        }

        // Store token and API key in WordPress database
        if (isset($body['token']) && isset($body['apiKeys']) && !empty($body['apiKeys'])) {
            update_option('content_craft_ai_token', $body['token']);
            update_option('content_craft_ai_api_key', $body['apiKeys'][0]['key']);
        }

        return rest_ensure_response($body);
    } catch (Exception $e) {
        return new WP_Error(
            'login_error',
            $e->getMessage(),
            array('status' => 500)
        );
    }
}
