<?php
if (!defined('ABSPATH')) {
    exit;
}
// includes/api.php

function wordchat_call_api($endpoint, $data) {
    $url = WORDCHAT_API_URL . $endpoint;

    // Append domain for server-side validation
    $data['domain'] = get_site_url();

    $response = wp_remote_post($url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($data),
        'timeout' => 15
    ]);

    if (is_wp_error($response)) {
        return ['error' => $response->get_error_message()];
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    return $body ?: ['error' => 'Invalid API response'];
}

function wordchat_send_query($question) {
    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');

    if (!$site_id || !$api_key) return ['error' => 'Missing site credentials'];

    return wordchat_call_api('/query', [
        'site_id' => $site_id,
        'api_key' => $api_key,
        'question' => $question
    ]);
}
