<?php

function docuchat_plugin_llmChat()
{
    echo wp_json_encode(docuchat_callLlm());
    wp_die();
}
function docuchat_callLlm()
{
    try {
        if (
            isset($_POST['message']) && !empty($_POST['message']) &&
            isset($_POST['token']) && !empty($_POST['token']) &&
            isset($_POST['nonce']) && !empty($_POST['nonce']) &&
            wp_verify_nonce( wp_unslash($_POST["nonce"]), 'llmChat')
        ) {

            $sanitized_unlashed_message = sanitize_file_name( wp_unslash( $_POST["message"]) );
            $sanitized_unlashed_token = sanitize_file_name( wp_unslash( $_POST["token"]) );

            $endpoint = 'https://api.docuchat.es/api/v1/conversation';

            $body = [
                'token'  =>  $sanitized_unlashed_token,
                'message' => $sanitized_unlashed_message,
            ];

            $body = wp_json_encode($body);

            $options = [
                'body'        => $body,
                'headers'     => [
                    'Content-Type' => 'application/json',
                ],
                'timeout'     => 60,
                'redirection' => 5,
                'blocking'    => true,
                'httpversion' => '1.0',
                'sslverify'   => false,
                'data_format' => 'body',
            ];

            $response = wp_remote_post($endpoint, $options);

 
            if (is_wp_error($response)) {
                return array("status" => 400, "message" => "Error registering data: " . $response->get_error_message());
            }

            return array("status" => 200, "message" => $response);
        }
    } catch (\Throwable $th) {
        return array("status" => 400, "message" => "Error registering data: " . $th->getMessage());
    }
}
