<?php
defined('ABSPATH') or die();
function aiomatic_agent_add_tool_results(&$reply, $add_me)
{
    do_action('aiomatic_tool_result', $add_me);
    if(isset($reply->aiomatic_tool_results) && is_array($reply->aiomatic_tool_results))
    {
        $reply->aiomatic_tool_results[] = $add_me;
    }
    else
    {
        $reply->aiomatic_tool_results = array($add_me);
    }
}
function aiomatic_agent_add_tool_direct_message(&$reply, $add_me)
{
    do_action('aiomatic_tool_direct_message', $add_me);
    if(isset($reply->aiomatic_tool_direct_message) && is_array($reply->aiomatic_tool_direct_message))
    {
        $reply->aiomatic_tool_direct_message[] = $add_me;
    }
    else
    {
        $reply->aiomatic_tool_direct_message = array($add_me);
    }
}
if (isset($this) && ($this instanceof Aiomatic_Agent))
{
    $agent = $this;
    $agent_god_mode_callback = function($reply, $query = array()) use ($agent) {
    if (isset($reply->tool_calls) && !empty($reply->tool_calls)) 
    {
        $ctx = apply_filters('aiomatic_agent_context', []);
        $current_agent = null;
        $current_step = 0;

        if (!empty($ctx['agent_id'])) {
            $current_agent = Aiomatic_Agent::get_instance_by_id((int)$ctx['agent_id']);
        }
        if (!$current_agent || !$current_agent->is_api_level_tool_execution_allowed()) {
            return $reply;
        }
        if (!empty($ctx['step'])) {
            $current_step = (int)$ctx['step'];
        }
        {
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            require_once(__DIR__ . '/res/amazon-direct.php');
            foreach($reply->tool_calls as $tool_call)
            {
                if (isset($tool_call->type) && $tool_call->type == 'function')
                {
                    $result = false;
                    if (isset($tool_call->function->arguments) && is_string($tool_call->function->arguments)) 
                    {
                        $targs = json_decode($tool_call->function->arguments);
                        if($targs !== null)
                        {
                            $tool_call->function->arguments = $targs;
                        }
                        else
                        {
                            $strips = stripslashes($tool_call->function->arguments);
                            $targs = json_decode($strips);
                            if($targs !== null)
                            {
                                $tool_call->function->arguments = $targs;
                            }
                            else
                            {
                                $jsons = aiomatic_parse_multiple_json($tool_call->function->arguments);
                                if(!empty($jsons) && isset($jsons[0]))
                                {
                                    $tool_call->function->arguments = $jsons[0];
                                }
                            }
                        }
                    }
                    if(!isset($tool_call->function) || !isset($tool_call->function->arguments) || !isset($tool_call->function->name))
                    {
                        continue;
                    }
                    if(isset($reply->choices[0]->message))
                    {
                        $as_mes = $reply->choices[0]->message;
                    }
                    else
                    {
                        $as_mes = '';
                    }
                    if ($current_agent) {
                        $args = $tool_call->function->arguments;

                        if (is_object($args)) {
                            $args = json_decode(wp_json_encode($args), true);
                        }
                        if (!is_array($args)) {
                            $args = [];
                        }

                        $current_agent->log_native_tool_call(
                            $current_step,
                            $tool_call->function->name,
                            $args
                        );
                        if($current_agent->is_debug_mode())
                        {
                            $current_agent->debug_log('CALLING TOOL [' . $tool_call->function->name . ']: ' . print_r($args, true));
                        }

                    }
                    if (!aiomatic_is_restricted_function_allowed($tool_call->function->name)) {
                        if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                        {
                            aiomatic_log_to_file('Blocked tool (central filter): ' . $tool_call->function->name);
                        }
                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => 'You are not allowed to call this function (you need to be admin)',
                            'assistant_message' => $as_mes
                        ));
                        continue;
                    }
                    if ($tool_call->function->name === 'generate_chart') 
                    {
                        if(isset($tool_call->function->arguments->shortcode))
                        {
                            $shortcode = $tool_call->function->arguments->shortcode;
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => do_shortcode($shortcode),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'shortcode parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_openai') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (!isset($aiomatic_Main_Settings['app_id'])) 
                            {
                                $aiomatic_Main_Settings['app_id'] = '';
                            }
                            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
                            $appids = array_filter($appids);
                            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
                            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
                            if (empty($token))
                            {
                                aiomatic_log_to_file('You need to enter an OpenAI API key for this to work!');
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size']) && trim($aiomatic_Chatbot_Settings['ai_image_size']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_model']) && trim($aiomatic_Chatbot_Settings['ai_image_model']) != '')
                            {
                                $model = trim($aiomatic_Chatbot_Settings['ai_image_model']);
                            }
                            else
                            {
                                $model = 'gpt-image-2';
                            }
                            if(empty($result))
                            {
                                $aierror = '';
                                $airesult = aiomatic_generate_ai_image($token, 1, $prompt, $image_size, 'chatFunctionDalleImage', false, 0, $aierror, $model, $prompt);
                                if($airesult !== false && is_array($airesult))
                                {
                                    foreach($airesult as $tmpimg)
                                    {
                                        $tmpimg = aiomatic_sanitize_image_src($tmpimg);
                                        if($tmpimg !== false)
                                        {
                                            $result = '<img class="image_max_w_ai" src="' . $tmpimg . '">';
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Dall-E image in AI chatbot: ' . $aierror);
                                    if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                    {
                                        $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                    }
                                    else
                                    {
                                        $result = 'Image creation failed, please try again later.';
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => $result,
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_stable_diffusion') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_stable']) && trim($aiomatic_Chatbot_Settings['ai_image_size_stable']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_stable']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            if (isset($aiomatic_Chatbot_Settings['stable_model']) && trim($aiomatic_Chatbot_Settings['stable_model']) != '')
                            {
                                $model = trim($aiomatic_Chatbot_Settings['stable_model']);
                            }
                            else
                            {
                                $model = AIMOGEN_STABLE_DEFAULT_MODE;
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_stability_image($prompt, $height, $width, 'chatFunctionStableImage', 0, false, $aierror, false, $model, '', 0);
                            if($airesult !== false && isset($airesult[1]))
                            {
                                $airesult[1] = aiomatic_sanitize_image_src($airesult[1]);
                                if($airesult[1] !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult[1] . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Stable image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_google') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                            {
                                $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                            }
                            else
                            {
                                $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_image_google($prompt, $model, 'chatFunctionGoogleImage', false, $aierror, false);
                            if($airesult !== false && isset($airesult[1]))
                            {
                                $airesult[1] = aiomatic_sanitize_image_src($airesult[1]);
                                if($airesult[1] !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult[1] . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Stable image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_midjourney') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_midjourney']) && trim($aiomatic_Chatbot_Settings['ai_image_size_midjourney']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_midjourney']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_ai_image_midjourney($prompt, $width, $height, 'chatFunctionMidjourneyImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Midjourney image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_replicate') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_replicate']) && trim($aiomatic_Chatbot_Settings['ai_image_size_replicate']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_replicate']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_replicate_image($prompt, $width, $height, 'chatFunctionReplicateImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Replicate image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_ideogram') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_ideogram']) && trim($aiomatic_Chatbot_Settings['ai_image_size_ideogram']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_ideogram']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_ideogram_image($prompt, $width, $height, 'chatFunctionIdeogramImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Ideogram image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_image_cloudflare') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $image_size = '512x512';
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_cloudflare_image($prompt, $width, $height, 'chatFunctionCloudflareImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Cloudflare image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'create_stable_diffusion_video') 
                    {
                        if(isset($tool_call->function->arguments->image_url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $image_url = $tool_call->function->arguments->image_url;
                            if (empty($image_url))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_video_size_stable']) && trim($aiomatic_Chatbot_Settings['ai_video_size_stable']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_video_size_stable']);
                            }
                            else
                            {
                                $image_size = '768x768';
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_stability_video($image_url, $image_size, 'chatbotStableVideo', 0, false, $aierror, false);
                            if($response_text !== false && isset($response_text[1]))
                            {
                                $result = '<div style="padding-bottom:56.25%; position:relative; display:block; width: 100%"><iframe src="' . $response_text[1] . '" width="100%" height="100%" style="position:absolute; top:0; left: 0" allowfullscreen webkitallowfullscreen frameborder="0"></iframe></div>';
                                aiomatic_agent_add_tool_direct_message($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate video in AI chatbot: ' . $aierror);
                                $result = 'Video creation failed, please try again later.';
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'search_amazon') 
                    {
                        if(isset($tool_call->function->arguments->query))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $asin = $tool_call->function->arguments->query;
                            if (empty($asin)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty search query provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['affiliate_id']) && trim($aiomatic_Chatbot_Settings['affiliate_id']) != '')
                            {
                                $aff_id = trim($aiomatic_Chatbot_Settings['affiliate_id']);
                            }
                            else
                            {
                                $aff_id = '';
                            }
                            if (isset($aiomatic_Chatbot_Settings['target_country']) && trim($aiomatic_Chatbot_Settings['target_country']) != '')
                            {
                                $target_country = trim($aiomatic_Chatbot_Settings['target_country']);
                            }
                            else
                            {
                                $target_country = 'com';
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_products']) && trim($aiomatic_Chatbot_Settings['max_products']) != '')
                            {
                                $max_product_count = trim($aiomatic_Chatbot_Settings['max_products']);
                            }
                            else
                            {
                                $max_product_count = '3-4';
                            }
                            if (isset($aiomatic_Chatbot_Settings['sort_results']) && trim($aiomatic_Chatbot_Settings['sort_results']) != '')
                            {
                                $amaz_sort_results = trim($aiomatic_Chatbot_Settings['sort_results']);
                            }
                            else
                            {
                                $amaz_sort_results = 'none';
                            }
                            if (isset($aiomatic_Chatbot_Settings['listing_template']) && trim($aiomatic_Chatbot_Settings['listing_template']) != '')
                            {
                                $listing_template = trim($aiomatic_Chatbot_Settings['listing_template']);
                            }
                            else
                            {
                                $listing_template = '%%product_counter%%. %%product_title%% - Desciption: %%product_description%% - Link: %%product_url%% - Price: %%product_price%%';
                            }
                            
                            if(strstr($max_product_count, '-') !== false)
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                if(is_numeric($minx) && is_numeric($maxx))
                                {
                                    $max_product_count = rand(intval($minx), intval($maxx));
                                }
                                else
                                {
                                    if(is_numeric($minx))
                                    {
                                        $max_product_count = intval($minx);
                                    }
                                    elseif(is_numeric($maxx))
                                    {
                                        $max_product_count = intval($maxx);
                                    }
                                    else
                                    {
                                        $max_product_count = 100;
                                    }
                                }
                            }
                            if(!empty($max_product_count) && is_numeric($max_product_count))
                            {
                                $max_prod = intval($max_product_count);
                            }
                            else
                            {
                                $max_prod = 100;
                            }
                            $amazresult = aiomatic_amazon_get_post($asin, trim($aff_id), $target_country, '', '', $amaz_sort_results, $max_prod, '1', array());
                            if(is_array($amazresult) && ((isset($amazresult['status']) && $amazresult['status'] == 'nothing') || count($amazresult) == 0))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No Amazon products found for query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'An error occurred while search Amazon for: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            
                            $final_result = '';
                            $counter = 1;
                            foreach($amazresult as $myprod)
                            {
                                $copy_template = $listing_template;
                                $copy_template = str_replace('%%product_counter%%', $counter, $copy_template);
                                $copy_template = str_replace('%%product_title%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_title)), $copy_template);
                                $copy_template = str_replace('%%product_description%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_desc)), $copy_template);
                                $copy_template = str_replace('%%product_url%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_url)), $copy_template);
                                $copy_template = str_replace('%%product_price%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_price)), $copy_template);
                                $copy_template = str_replace('%%product_list_price%%', trim(preg_replace('/\s+/', ' ', $myprod->product_list_price)), $copy_template);
                                $copy_template = str_replace('%%product_image%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_img)), $copy_template);
                                $copy_template = str_replace('%%product_cart_url%%', trim(preg_replace('/\s+/', ' ', $myprod->cart_url)), $copy_template);
                                $copy_template = str_replace('%%product_images_urls%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs)), $copy_template);
                                $copy_template = str_replace('%%product_images%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs_html)), $copy_template);
                                $copy_template = str_replace('%%product_reviews%%', trim(preg_replace('/\s+/', ' ', implode(PHP_EOL, $myprod->item_reviews))), $copy_template);
                                //new
                                $copy_template = str_replace('%%product_score%%', trim(preg_replace('/\s+/', ' ', $myprod->item_score)), $copy_template);
                                $copy_template = str_replace('%%product_language%%', trim(preg_replace('/\s+/', ' ', $myprod->language)), $copy_template);
                                $copy_template = str_replace('%%product_edition%%', trim(preg_replace('/\s+/', ' ', $myprod->edition)), $copy_template);
                                $copy_template = str_replace('%%product_pages_count%%', trim(preg_replace('/\s+/', ' ', $myprod->pages_count)), $copy_template);
                                $copy_template = str_replace('%%product_publication_date%%', trim(preg_replace('/\s+/', ' ', $myprod->publication_date)), $copy_template);
                                $copy_template = str_replace('%%product_contributors%%', trim(preg_replace('/\s+/', ' ', $myprod->contributors)), $copy_template);
                                $copy_template = str_replace('%%product_manufacturer%%', trim(preg_replace('/\s+/', ' ', $myprod->manufacturer)), $copy_template);
                                $copy_template = str_replace('%%product_binding%%', trim(preg_replace('/\s+/', ' ', $myprod->binding)), $copy_template);
                                $copy_template = str_replace('%%product_product_group%%', trim(preg_replace('/\s+/', ' ', $myprod->product_group)), $copy_template);
                                $copy_template = str_replace('%%product_rating%%', trim(preg_replace('/\s+/', ' ', $myprod->rating)), $copy_template);
                                $copy_template = str_replace('%%product_ean%%', trim(preg_replace('/\s+/', ' ', $myprod->eans)), $copy_template);
                                $copy_template = str_replace('%%product_part_no%%', trim(preg_replace('/\s+/', ' ', $myprod->part_no)), $copy_template);
                                $copy_template = str_replace('%%product_model%%', trim(preg_replace('/\s+/', ' ', $myprod->model)), $copy_template);
                                $copy_template = str_replace('%%product_warranty%%', trim(preg_replace('/\s+/', ' ', $myprod->warranty)), $copy_template);
                                $copy_template = str_replace('%%product_color%%', trim(preg_replace('/\s+/', ' ', $myprod->color)), $copy_template);
                                $copy_template = str_replace('%%product_is_adult%%', trim(preg_replace('/\s+/', ' ', $myprod->is_adult)), $copy_template);
                                $copy_template = str_replace('%%product_dimensions%%', trim(preg_replace('/\s+/', ' ', $myprod->dimensions)), $copy_template);
                                $copy_template = str_replace('%%product_size%%', trim(preg_replace('/\s+/', ' ', $myprod->size)), $copy_template);
                                $copy_template = str_replace('%%product_unit_count%%', trim(preg_replace('/\s+/', ' ', $myprod->unit_count)), $copy_template);
                                
                                $counter++;
                                $final_result .= $copy_template . '\r\n'; 
                            }
                            $final_result = trim($final_result);
                            $final_result = aiomatic_substr($final_result, 0, 400000);
                            if(!empty($final_result))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                            else
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Amazon did not return info for this query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'search_clickbank') 
                    {
                        if(isset($tool_call->function->arguments->query))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $asin = $tool_call->function->arguments->query;
                            if (empty($asin)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty search query provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['clickbank_affiliate_id']) && trim($aiomatic_Chatbot_Settings['clickbank_affiliate_id']) != '')
                            {
                                $cb_affiliate_id = trim($aiomatic_Chatbot_Settings['clickbank_affiliate_id']);
                            }
                            else
                            {
                                $cb_affiliate_id = '';
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_products_cb']) && trim($aiomatic_Chatbot_Settings['max_products_cb']) != '')
                            {
                                $max_product_count = trim($aiomatic_Chatbot_Settings['max_products_cb']);
                            }
                            else
                            {
                                $max_product_count = '3-4';
                            }
                            if (isset($aiomatic_Chatbot_Settings['listing_template_cb']) && trim($aiomatic_Chatbot_Settings['listing_template_cb']) != '')
                            {
                                $listing_template = trim($aiomatic_Chatbot_Settings['listing_template_cb']);
                            }
                            else
                            {
                                $listing_template = '%%product_counter%%. %%product_title%% - Desciption: %%product_description%% - Link: %%product_url%% - Price: %%product_price%%';
                            }
                            
                            if(strstr($max_product_count, '-') !== false)
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                if(is_numeric($minx) && is_numeric($maxx))
                                {
                                    $max_product_count = rand(intval($minx), intval($maxx));
                                }
                                else
                                {
                                    if(is_numeric($minx))
                                    {
                                        $max_product_count = intval($minx);
                                    }
                                    elseif(is_numeric($maxx))
                                    {
                                        $max_product_count = intval($maxx);
                                    }
                                    else
                                    {
                                        $max_product_count = 100;
                                    }
                                }
                            }
                            if(!empty($max_product_count) && is_numeric($max_product_count))
                            {
                                $max_prod = intval($max_product_count);
                            }
                            else
                            {
                                $max_prod = 100;
                            }
                            $neg_keywords = '';
                            $item_category = 'All';
                            $shipable_only = '';
                            $pitch_plus = '';
                            $one_time = '';
                            $recurring = '';
                            $affiliate_tools = '';
                            $spotlight = '';
                            $mobile_hoplink = '';
                            $item_language = '';
                            $activation = '';
                            $item_gravity = '';
                            $dollar_sale = '';
                            $dollar_sale_av = '';
                            $rebill_total = '';
                            $per_sale = '';
                            $per_rebill = '';
                            $sort_results_cb = '';
                            $amazresult = aiomatic_clickbank_get_post($cb_affiliate_id, $asin, $neg_keywords, $item_category, $shipable_only, $pitch_plus, $one_time, $recurring, $affiliate_tools, $spotlight, $mobile_hoplink, $item_language, $activation, $item_gravity, $dollar_sale, $dollar_sale_av, $rebill_total, $per_sale, $per_rebill, $sort_results_cb, $max_prod);
                            if(is_array($amazresult) && ((isset($amazresult['status']) && $amazresult['status'] == 'nothing') || count($amazresult) == 0))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No ClickBank products found for query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'An error occurred while search ClickBank for: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            
                            $final_result = '';
                            $counter = 1;
                            foreach($amazresult as $myprod)
                            {
                                $copy_template = $listing_template;
                                $copy_template = str_replace('%%product_counter%%', $counter, $copy_template);
                                $copy_template = str_replace('%%product_title%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_title)), $copy_template);
                                $copy_template = str_replace('%%product_description%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_desc)), $copy_template);
                                $copy_template = str_replace('%%product_url%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_url)), $copy_template);
                                $copy_template = str_replace('%%product_price%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_price)), $copy_template);
                                $copy_template = str_replace('%%product_list_price%%', trim(preg_replace('/\s+/', ' ', $myprod->product_list_price)), $copy_template);
                                $copy_template = str_replace('%%product_image%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_img)), $copy_template);
                                $copy_template = str_replace('%%product_cart_url%%', trim(preg_replace('/\s+/', ' ', $myprod->cart_url)), $copy_template);
                                $copy_template = str_replace('%%product_images_urls%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs)), $copy_template);
                                $copy_template = str_replace('%%product_images%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs_html)), $copy_template);
                                $copy_template = str_replace('%%product_reviews%%', trim(preg_replace('/\s+/', ' ', implode(PHP_EOL, $myprod->item_reviews))), $copy_template);
                                //new
                                $copy_template = str_replace('%%product_score%%', trim(preg_replace('/\s+/', ' ', $myprod->item_score)), $copy_template);
                                $copy_template = str_replace('%%product_language%%', trim(preg_replace('/\s+/', ' ', $myprod->language)), $copy_template);
                                $copy_template = str_replace('%%product_edition%%', trim(preg_replace('/\s+/', ' ', $myprod->edition)), $copy_template);
                                $copy_template = str_replace('%%product_pages_count%%', trim(preg_replace('/\s+/', ' ', $myprod->pages_count)), $copy_template);
                                $copy_template = str_replace('%%product_publication_date%%', trim(preg_replace('/\s+/', ' ', $myprod->publication_date)), $copy_template);
                                $copy_template = str_replace('%%product_contributors%%', trim(preg_replace('/\s+/', ' ', $myprod->contributors)), $copy_template);
                                $copy_template = str_replace('%%product_manufacturer%%', trim(preg_replace('/\s+/', ' ', $myprod->manufacturer)), $copy_template);
                                $copy_template = str_replace('%%product_binding%%', trim(preg_replace('/\s+/', ' ', $myprod->binding)), $copy_template);
                                $copy_template = str_replace('%%product_product_group%%', trim(preg_replace('/\s+/', ' ', $myprod->product_group)), $copy_template);
                                $copy_template = str_replace('%%product_rating%%', trim(preg_replace('/\s+/', ' ', $myprod->rating)), $copy_template);
                                $copy_template = str_replace('%%product_ean%%', trim(preg_replace('/\s+/', ' ', $myprod->eans)), $copy_template);
                                $copy_template = str_replace('%%product_part_no%%', trim(preg_replace('/\s+/', ' ', $myprod->part_no)), $copy_template);
                                $copy_template = str_replace('%%product_model%%', trim(preg_replace('/\s+/', ' ', $myprod->model)), $copy_template);
                                $copy_template = str_replace('%%product_warranty%%', trim(preg_replace('/\s+/', ' ', $myprod->warranty)), $copy_template);
                                $copy_template = str_replace('%%product_color%%', trim(preg_replace('/\s+/', ' ', $myprod->color)), $copy_template);
                                $copy_template = str_replace('%%product_is_adult%%', trim(preg_replace('/\s+/', ' ', $myprod->is_adult)), $copy_template);
                                $copy_template = str_replace('%%product_dimensions%%', trim(preg_replace('/\s+/', ' ', $myprod->dimensions)), $copy_template);
                                $copy_template = str_replace('%%product_size%%', trim(preg_replace('/\s+/', ' ', $myprod->size)), $copy_template);
                                $copy_template = str_replace('%%product_unit_count%%', trim(preg_replace('/\s+/', ' ', $myprod->unit_count)), $copy_template);
                                
                                $counter++;
                                $final_result .= $copy_template . '\r\n'; 
                            }
                            $final_result = trim($final_result);
                            $final_result = aiomatic_substr($final_result, 0, 400000);
                            if(!empty($final_result))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                            else
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'ClickBank did not return info for this query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'get_amazon_product_details') 
                    {
                        if(isset($tool_call->function->arguments->query))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $asin = $tool_call->function->arguments->query;
                            if (empty($asin)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty search query provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['affiliate_id']) && trim($aiomatic_Chatbot_Settings['affiliate_id']) != '')
                            {
                                $aff_id = trim($aiomatic_Chatbot_Settings['affiliate_id']);
                            }
                            else
                            {
                                $aff_id = '';
                            }
                            if (isset($aiomatic_Chatbot_Settings['target_country']) && trim($aiomatic_Chatbot_Settings['target_country']) != '')
                            {
                                $target_country = trim($aiomatic_Chatbot_Settings['target_country']);
                            }
                            else
                            {
                                $target_country = 'com';
                            }
                            $max_prod = 1;
                            $amazresult = aiomatic_amazon_get_post($asin, trim($aff_id), $target_country, '', '', '', $max_prod, '1', array());
                            if(is_array($amazresult) && ((isset($amazresult['status']) && $amazresult['status'] == 'nothing') || count($amazresult) == 0))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No Amazon products found for query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'An error occurred while search Amazon for: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $final_result = 'Product title: ' . $amazresult[0]->offer_title . '\n';
                                $final_result .= 'Description: ' . $amazresult[0]->offer_desc . '\n';
                                $final_result .= 'URL: ' . $amazresult[0]->offer_url . '\n';
                                $final_result .= 'Price: ' . $amazresult[0]->offer_price . '\n';
                                $final_result .= 'Listing Price: ' . $amazresult[0]->product_list_price . '\n';
                                $final_result .= 'Image: ' . $amazresult[0]->offer_img . '\n';
                                $final_result .= 'Add to cart URL: ' . $amazresult[0]->cart_url . '\n';
                                $final_result .= 'Other images: ' . $amazresult[0]->product_imgs . '\n';
                                //new
                                if(!empty($amazresult[0]->item_score))
                                {
                                    $final_result .= 'Score: ' . $amazresult[0]->item_score . '\n';
                                }
                                if(!empty($amazresult[0]->language))
                                {
                                    $final_result .= 'Language: ' . $amazresult[0]->language . '\n';
                                }
                                if(!empty($amazresult[0]->edition))
                                {
                                    $final_result .= 'Edition: ' . $amazresult[0]->edition . '\n';
                                }
                                if(!empty($amazresult[0]->pages_count))
                                {
                                    $final_result .= 'Pages Count: ' . $amazresult[0]->pages_count . '\n';
                                }
                                if(!empty($amazresult[0]->publication_date))
                                {
                                    $final_result .= 'Date: ' . $amazresult[0]->publication_date . '\n';
                                }
                                if(!empty($amazresult[0]->contributors))
                                {
                                    $final_result .= 'Contributors: ' . $amazresult[0]->contributors . '\n';
                                }
                                if(!empty($amazresult[0]->manufacturer))
                                {
                                    $final_result .= 'Manufacturer: ' . $amazresult[0]->manufacturer . '\n';
                                }
                                if(!empty($amazresult[0]->binding))
                                {
                                    $final_result .= 'Binding: ' . $amazresult[0]->binding . '\n';
                                }
                                if(!empty($amazresult[0]->product_group))
                                {
                                    $final_result .= 'Product Group: ' . $amazresult[0]->product_group . '\n';
                                }
                                if(!empty($amazresult[0]->rating))
                                {
                                    $final_result .= 'Rating: ' . $amazresult[0]->rating . '\n';
                                }
                                if(!empty($amazresult[0]->eans))
                                {
                                    $final_result .= 'EAN: ' . $amazresult[0]->eans . '\n';
                                }
                                if(!empty($amazresult[0]->part_no))
                                {
                                    $final_result .= 'Part No: ' . $amazresult[0]->part_no . '\n';
                                }
                                if(!empty($amazresult[0]->model))
                                {
                                    $final_result .= 'Model: ' . $amazresult[0]->model . '\n';
                                }
                                if(!empty($amazresult[0]->warranty))
                                {
                                    $final_result .= 'Warranty: ' . $amazresult[0]->warranty . '\n';
                                }
                                if(!empty($amazresult[0]->color))
                                {
                                    $final_result .= 'Color: ' . $amazresult[0]->color . '\n';
                                }
                                if(!empty($amazresult[0]->is_adult))
                                {
                                    $final_result .= 'Is Adult: ' . $amazresult[0]->is_adult . '\n';
                                }
                                if(!empty($amazresult[0]->dimensions))
                                {
                                    $final_result .= 'Dimensions: ' . $amazresult[0]->dimensions . '\n';
                                }
                                if(!empty($amazresult[0]->size))
                                {
                                    $final_result .= 'Size: ' . $amazresult[0]->size . '\n';
                                }
                                if(!empty($amazresult[0]->unit_count))
                                {
                                    $final_result .= 'Unit Count: ' . $amazresult[0]->unit_count . '\n';
                                }
                                $final_result .= 'Reviews: ' . implode(PHP_EOL, $amazresult[0]->item_reviews) . '\n';
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'manage_booking_calendar_booking') 
                    {
                        if (!empty($tool_call->function->arguments->start_date) && !empty($tool_call->function->arguments->end_date) && !empty($tool_call->function->arguments->name) && !empty($tool_call->function->arguments->email)) 
                        {
                            $start_date  = sanitize_text_field($tool_call->function->arguments->start_date);
                            $end_date    = sanitize_text_field($tool_call->function->arguments->end_date);
                            $name        = sanitize_text_field($tool_call->function->arguments->name);
                            $email       = sanitize_email($tool_call->function->arguments->email);
                            $secondname  = isset($tool_call->function->arguments->secondname) ? sanitize_text_field($tool_call->function->arguments->secondname) : '';
                            $resource_id = isset($tool_call->function->arguments->resource_id) ? intval($tool_call->function->arguments->resource_id) : 1;

                            if (!function_exists('wpbc_api_is_dates_booked') || !function_exists('wpbc_api_booking_add_new')) {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Booking Calendar API functions are not available.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $dates = [$start_date, $end_date];
                            $params = ['is_use_booking_recurrent_time' => false];

                            $is_booked = wpbc_api_is_dates_booked($dates, $resource_id, $params);
                            if ($is_booked) {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'These dates are already booked, select different dates',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $data = [
                                'name'       => $name,
                                'email'      => ['value' => $email, 'type' => 'email'],
                                'secondname' => ['value' => $secondname, 'type' => 'text']
                            ];

                            $booking_id = wpbc_api_booking_add_new($dates, $data, $resource_id);

                            if ($booking_id) {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Booking created: ' . $booking_id,
                                    'assistant_message' => $as_mes
                                ));
                            } else {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to create booking.',
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Arguments not set for the booking function call.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }
                    }
                    elseif ($tool_call->function->name === 'aimogen_content_editor_templates') 
                    {
                        $args = $tool_call->function->arguments ?? null;

                        if(!$args)
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'arguments missing',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $operation   = $args->operation ?? '';
                        $post_id     = isset($args->post_id) ? intval($args->post_id) : 0;
                        $template_id = isset($args->template_id) ? intval($args->template_id) : 0;

                        if (empty($operation)) 
                        {
                            if(empty($post_id) || empty($template_id))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: operation parameter missing',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aimogen_content_editor_templates_list(),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($post_id <= 0) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid post_id',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $post_obj = get_post($post_id);
                            if (!$post_obj) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Post not found',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $template_to_run = 'skip';

                            if ($template_id > 0) 
                            {
                                $template_post = get_post($template_id);
                                if (!$template_post || $template_post->post_type !== 'aiomatic_editor_temp') 
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Invalid template_id',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }
                                $template_to_run = $template_id;
                            }

                            aiomatic_do_post($post_obj, true, $template_to_run, false);

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $template_id > 0
                                    ? 'Template applied successfully'
                                    : 'Executed with default template logic',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        aiomatic_agent_add_tool_results($reply, [
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => 'Invalid operation',
                            'assistant_message' => $as_mes
                        ]);
                    }
                    elseif ($tool_call->function->name === 'get_post_structure') 
                    {
                        $args = $tool_call->function->arguments ?? null;

                        if(!$args)
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'arguments missing',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $post_id = isset($args->post_id) ? intval($args->post_id) : 0;

                        if ($post_id <= 0) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: post_id is required',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $post = get_post($post_id);

                        if (!$post) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Post not found',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $content = $post->post_content;

                        if (empty($content)) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: Empty content',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $blocks = function_exists('parse_blocks') ? parse_blocks($content) : [];
                        $html = !empty($blocks) ? render_block_data_recursive($blocks) : $content;

                        libxml_use_internal_errors(true);
                        $dom = new DOMDocument();
                        $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
                        libxml_clear_errors();

                        $xpath = new DOMXPath($dom);

                        $structure = [];

                        $headings = $xpath->query('//h2 | //h3 | //h4');

                        foreach ($headings as $node) 
                        {
                            $text = trim(preg_replace('/\s+/', ' ', $node->textContent));

                            if ($text === '') {
                                continue;
                            }

                            $structure[] = [
                                'type' => strtolower($node->nodeName),
                                'text' => $text,
                                'selector' => strtolower($node->nodeName) . ':' . $text
                            ];
                        }
                        $paragraphs = $xpath->query('//p');

                        $result = [
                            'total_paragraphs' => $paragraphs ? $paragraphs->length : 0,
                            'sections' => $structure,
                            'suggested_selectors' => array_values(array_map(function($s){
                                return $s['selector'];
                            }, $structure))
                        ];

                        aiomatic_agent_add_tool_direct_message($reply, [
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => wp_json_encode($result),
                            'assistant_message' => $as_mes
                        ]);

                        continue;
                    }
                    elseif ($tool_call->function->name === 'aimogen_rules_engine') 
                    {
                        $args = $tool_call->function->arguments ?? null;

                        if(!$args)
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'arguments missing',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $operation = $args->operation ?? '';
                        $rule_id   = $args->rule_id ?? '';
                        $rule_type = $args->rule_type ?? '';

                        if (empty($operation)) 
                        {
                            if(empty($rule_id) || empty($rule_type))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'operation missing',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aimogen_rules_engine_list(),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($rule_id === null || $rule_type === null) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Missing rule_id or rule_type',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $result = aiomatic_run_rule($rule_id, $rule_type, 0, 0, null, '', '', false, []);

                            if ($result === 'fail') 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Execution failed',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            if ($result === 'nochange') 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No new content generated',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Rule executed successfully',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        aiomatic_agent_add_tool_results($reply, [
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => 'Invalid operation',
                            'assistant_message' => $as_mes
                        ]);
                    }
                    elseif ($tool_call->function->name === 'edit_post_section') 
                    {
                        $args = $tool_call->function->arguments ?? null;

                        if (!$args) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'arguments missing',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $post_id     = isset($args->post_id) ? intval($args->post_id) : 0;
                        $selector    = isset($args->section_selector) ? sanitize_text_field($args->section_selector) : '';
                        $instruction = isset($args->instruction) ? trim(wp_kses_post($args->instruction)) : '';

                        if ($post_id <= 0 || $selector === '' || $instruction === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: post_id, section_selector and instruction are required.',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $post = get_post($post_id);

                        if (!$post) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Post with ID " . $post_id . " not found.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $content = $post->post_content;

                        if (trim($content) === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Post content is empty.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $blocks          = function_exists('parse_blocks') ? parse_blocks($content) : [];
                        $is_block_editor = function_exists('has_blocks') ? has_blocks($content) : !empty($blocks);
                        $html            = ($is_block_editor && function_exists('render_block_data_recursive')) ? render_block_data_recursive($blocks) : $content;

                        if (trim($html) === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to prepare post HTML.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        libxml_use_internal_errors(true);

                        $dom = new DOMDocument('1.0', 'UTF-8');

                        $loaded = $dom->loadHTML(
                            '<?xml encoding="utf-8" ?><html><body>' . $html . '</body></html>',
                            LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
                        );

                        libxml_clear_errors();

                        if (!$loaded) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to parse post HTML.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $body = $dom->getElementsByTagName('body')->item(0);

                        if (!$body) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to locate parsed HTML body.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $xpath       = new DOMXPath($dom);
                        $target_node = null;

                        if ($selector === 'full_content') 
                        {
                            $target_node = $body;
                        }
                        elseif ($selector === 'first_paragraph') 
                        {
                            $nodes = $xpath->query('//p');
                            if ($nodes && $nodes->length > 0) {
                                $target_node = $nodes->item(0);
                            }
                        }
                        elseif ($selector === 'last_paragraph') 
                        {
                            $nodes = $xpath->query('//p');
                            if ($nodes && $nodes->length > 0) {
                                $target_node = $nodes->item($nodes->length - 1);
                            }
                        }
                        elseif (strpos($selector, 'paragraph:') === 0) 
                        {
                            $num   = max(0, ((int) str_replace('paragraph:', '', $selector)) - 1);
                            $nodes = $xpath->query('//p');

                            if ($nodes && $nodes->length > $num) {
                                $target_node = $nodes->item($num);
                            }
                        }
                        elseif (preg_match('/^h([2-4]):(.+)$/', $selector, $m)) 
                        {
                            $tag  = 'h' . $m[1];
                            $text = trim($m[2]);

                            $nodes = $xpath->query('//' . $tag);

                            if ($nodes) 
                            {
                                foreach ($nodes as $node) 
                                {
                                    if (stripos(trim($node->textContent), $text) !== false) 
                                    {
                                        $target_node = $node;
                                        break;
                                    }
                                }
                            }
                        }

                        if (!$target_node) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Could not locate section for selector '" . $selector . "'.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        if ($selector === 'full_content') 
                        {
                            $target_html = '';

                            foreach ($body->childNodes as $child) {
                                $target_html .= $dom->saveHTML($child);
                            }
                        } 
                        else 
                        {
                            $target_html = $dom->saveHTML($target_node);
                        }

                        if (trim($target_html) === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed extracting target content.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $prompt = "You are editing HTML content.

                    STRICT RULES:
                    - Do NOT remove any existing content unless the instruction clearly asks for it
                    - Do NOT shorten text unless the instruction clearly asks for it
                    - Do NOT remove links or formatting
                    - Keep all HTML tags valid
                    - Return valid HTML only
                    - Do NOT add explanations or comments

                    Instruction:
                    {$instruction}

                    === ORIGINAL CONTENT START ===
                    {$target_html}
                    === ORIGINAL CONTENT END ===

                    Return ONLY the edited HTML.";

                        $model = $this->model;

                        $settings = get_option('aiomatic_Main_Settings', false);
                        $appids   = [];

                        if (is_array($settings) && !empty($settings['app_id'])) {
                            $appids = array_filter(preg_split('/\r\n|\r|\n/', trim($settings['app_id'])));
                        }

                        $token = !empty($appids) ? $appids[array_rand($appids)] : '';
                        $token = apply_filters('aiomatic_openai_api_key', $token);

                        if (empty($token)) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: OpenAI API key is missing.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $query_token_count = count(aiomatic_encode($prompt));
                        $max_tokens        = aimogenpro_get_max_tokens($model);

                        $available_tokens = aiomatic_compute_available_tokens(
                            $model,
                            $max_tokens,
                            $prompt,
                            $query_token_count
                        );

                        if ($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) 
                        {
                            $cut    = intval(aiomatic_strlen($prompt) / 2);
                            $prompt = trim(aiomatic_substr($prompt, 0, -$cut));

                            $query_token_count = count(aiomatic_encode($prompt));
                            $available_tokens  = $max_tokens - $query_token_count;
                        }

                        if ($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Not enough available tokens to edit this section.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $thread_id     = '';
                        $aierror       = '';
                        $finish_reason = '';

                        if ($this->is_debug_mode()) {
                            $this->debug_log('Editing post section: ' . print_r($prompt, true));
                        }

                        $edited = aiomatic_generate_text(
                            $token,
                            $model,
                            $prompt,
                            $available_tokens,
                            0.2,
                            1,
                            0,
                            0,
                            false,
                            'agentsEdit',
                            0,
                            $finish_reason,
                            $aierror,
                            false,
                            false,
                            false,
                            '',
                            '',
                            'user',
                            '',
                            $thread_id,
                            '',
                            'disabled',
                            '',
                            false,
                            false,
                            [],
                            '',
                            '',
                            ''
                        );

                        if ($this->is_debug_mode()) {
                            $this->debug_log('Editing post section response: ' . print_r($edited, true));
                        }

                        if (!empty($aierror)) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: AI error - " . $aierror,
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        if (empty($edited)) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: AI returned empty result.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $edited = trim($edited);
                        $edited = preg_replace('/^\s*```(?:html)?\s*/i', '', $edited);
                        $edited = preg_replace('/\s*```\s*$/', '', $edited);
                        $edited = preg_replace('#</?(?:html|body)[^>]*>#i', '', $edited);
                        $edited = trim($edited);

                        if ($edited === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: AI returned empty HTML after cleanup.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $fragment = $dom->createDocumentFragment();

                        if (!@$fragment->appendXML($edited)) 
                        {
                            $tmp = new DOMDocument('1.0', 'UTF-8');

                            libxml_use_internal_errors(true);

                            $tmp_loaded = $tmp->loadHTML(
                                '<?xml encoding="utf-8" ?><html><body><div id="aiomatic_tmp_wrapper">' . $edited . '</div></body></html>',
                                LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
                            );

                            libxml_clear_errors();

                            if (!$tmp_loaded) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Invalid HTML returned by AI.",
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $tmp_xpath = new DOMXPath($tmp);
                            $wrapper   = $tmp_xpath->query('//*[@id="aiomatic_tmp_wrapper"]')->item(0);

                            if (!$wrapper) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Could not parse edited HTML wrapper.",
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            foreach ($wrapper->childNodes as $child) 
                            {
                                $fragment->appendChild($dom->importNode($child, true));
                            }

                            if (!$fragment->hasChildNodes()) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Edited HTML contains no usable nodes.",
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                        }

                        if ($selector === 'full_content') 
                        {
                            while ($body->firstChild) {
                                $body->removeChild($body->firstChild);
                            }

                            $body->appendChild($fragment);
                        } 
                        else 
                        {
                            if (!$target_node->parentNode) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Target node has no parent.",
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $target_node->parentNode->replaceChild($fragment, $target_node);
                        }

                        $body = $dom->getElementsByTagName('body')->item(0);

                        if (!$body) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to rebuild post HTML body.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $new_html = '';

                        foreach ($body->childNodes as $child) {
                            $new_html .= $dom->saveHTML($child);
                        }

                        $new_html = trim($new_html);

                        if ($new_html === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Edited content became empty. Update cancelled.",
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        $new_content = $is_block_editor
                            ? "<!-- wp:html -->\n" . $new_html . "\n<!-- /wp:html -->"
                            : $new_html;

                        $updated = wp_update_post([
                            'ID'           => $post_id,
                            'post_content' => $new_content
                        ], true);

                        if (is_wp_error($updated)) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error updating post: " . $updated->get_error_message(),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        aiomatic_agent_add_tool_direct_message($reply, [
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => "Success: post ID " . $post_id . " updated.",
                            'assistant_message' => $as_mes
                        ]);
                    }
                    elseif ($tool_call->function->name === 'list_available_ai_agents') 
                    {
                        $agents_query = new WP_Query([
                            'post_type' => 'aiomatic_agent',
                            'post_status' => 'publish',
                            'posts_per_page' => -1,
                        ]);

                        $agents = [];

                        if ($agents_query->have_posts()) 
                        {
                            $all_tools = Aiomatic_Agent::get_agent_tools();
                            $all_tool_names = array_keys($all_tools);
                            while ($agents_query->have_posts()) 
                            {
                                $agents_query->the_post();

                                $id = get_the_ID();
                                if ((int)$id === (int)$agent->get_agent_id()) continue;
                                $config = get_post_meta($id, '_agent_config', true);
                                $allowed_tools = [];

                                if (is_array($config)) {
                                    if (
                                        array_key_exists('allowed_tools', $config) &&
                                        is_array($config['allowed_tools']) &&
                                        !empty($config['allowed_tools'])
                                    ) {
                                        $allowed_tools = array_values($config['allowed_tools']);
                                    } else {
                                        $allowed_tools = $all_tool_names;
                                    }
                                } else {
                                    $allowed_tools = $all_tool_names;
                                }
                                $allowed_tools = array_values(array_intersect($allowed_tools, $all_tool_names));
                                $agents[] = [
                                    'agent_id' => $id,
                                    'agent_name' => get_the_title(),
                                    'description' => get_post_meta($id, 'aiomatic_agent_description', true),
                                    'expertise' => get_post_meta($id, 'aiomatic_agent_expertise', true),
                                    'tools'       => $allowed_tools,
                                    'capabilities' => [
                                        'can_publish' => (in_array('manage_wp_post', $allowed_tools) || in_array('edit_post_section', $allowed_tools)),
                                        'can_research' => in_array('google_results_parser', $allowed_tools),
                                        'can_scrape' => in_array('website_scraper', $allowed_tools),
                                        'can_email' => in_array('wp_send_email', $allowed_tools),
                                    ],
                                    'max_steps' => isset($config['max_steps']) ? intval($config['max_steps']) : 20,
                                    'model' => get_post_meta($id, '_model', true),
                                ];
                            }
                            wp_reset_postdata();
                        }

                        if (empty($agents)) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'No agents found',
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        aiomatic_agent_add_tool_direct_message($reply, [
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => wp_json_encode($agents),
                            'assistant_message' => $as_mes
                        ]);
                    }
                    elseif ($tool_call->function->name === 'delegate_to_ai_agent') 
                    {
                        $za_conf = $agent->get_config();

                        if (empty($za_conf['allow_delegation'])) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Delegation disabled",
                                    "instruction" => "Continue solving the task without delegation."
                                ]),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        if ($agent->get_is_sub_agent()) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Sub-agents cannot delegate",
                                    "instruction" => "Complete the task directly without further delegation."
                                ]),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        // Validate arguments existence
                        if (
                            !isset($tool_call->function->arguments->agent_id) ||
                            !isset($tool_call->function->arguments->task)
                        ) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Missing required parameters",
                                    "required" => ["agent_id", "task"],
                                    "instruction" => "Call list_available_ai_agents first, then retry delegate_to_ai_agent with both agent_id and task."
                                ]),
                                'assistant_message' => $as_mes
                            ]);
                            aiomatic_log_to_file('Invalid delegate call (missing params): ' . print_r($tool_call, true));
                            continue;
                        }

                        $agent_id = trim((string)$tool_call->function->arguments->agent_id);
                        $task     = trim((string)$tool_call->function->arguments->task);

                        // Validate empty values
                        if ($agent_id === '' || $task === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Empty parameters",
                                    "instruction" => "agent_id and task must not be empty. Retrieve a valid agent_id and retry."
                                ]),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        // Prevent self delegation
                        if ((int)$agent_id === (int)$agent->get_agent_id()) 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Invalid delegation target",
                                    "instruction" => "You cannot delegate to yourself. Choose a different agent_id."
                                ]),
                                'assistant_message' => $as_mes
                            ]);
                            continue;
                        }

                        // Execute delegation
                        $res = $agent->aiomatic_call_agent($agent_id, $task);

                        if (!empty($res)) 
                        {
                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $res,
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else 
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Agent execution failed",
                                    "instruction" => "Retry delegation or choose a different agent."
                                ]),
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'read_server_file') 
                    {
                        if(isset($tool_call->function->arguments->file_path))
                        {
                            $file_path = $tool_call->function->arguments->file_path;

                            $base_dir = WP_CONTENT_DIR;
                            $real_path = realpath(ABSPATH . ltrim($file_path, '/\\'));

                            if (!$real_path || strpos($real_path, $base_dir) !== 0) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Access denied',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $ext = pathinfo($real_path, PATHINFO_EXTENSION);
                            if (!in_array($ext, ['txt','log','csv','json'])) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid file type',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            if (!file_exists($real_path)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'File not found',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            
                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            $content = substr($wp_filesystem->get_contents($real_path), 0, 5000);

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $content,
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'write_server_file') 
                    {
                        if(isset($tool_call->function->arguments->filename) && isset($tool_call->function->arguments->content))
                        {
                            $filename  = $tool_call->function->arguments->filename;
                            $content   = $tool_call->function->arguments->content;
                            $overwrite = isset($tool_call->function->arguments->overwrite) ? (bool)$tool_call->function->arguments->overwrite : false;

                            // 1. Base sandbox directory
                            $upload_dir = wp_upload_dir();
                            $base_dir   = trailingslashit($upload_dir['basedir']) . 'aiomatic-exports/';

                            if (!file_exists($base_dir)) {
                                wp_mkdir_p($base_dir);
                            }

                            // Optional hardening
                            if (!file_exists($base_dir . 'index.php')) {
                                @file_put_contents($base_dir . 'index.php', "<?php\n// Silence is golden.\n");
                            }

                            // 2. Sanitize filename
                            $filename = sanitize_file_name($filename);

                            if (empty($filename) || basename($filename) !== $filename)
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid filename',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // 3. Extension validation
                            $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                            $allowed = ['txt','log','csv','json','md'];

                            if (empty($ext) || !in_array($ext, $allowed, true))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid file type',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // 4. Size limit
                            if (strlen($content) > 2 * 1024 * 1024)
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Content too large (max 2MB)',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // 5. Build safe path
                            $target_path = $base_dir . $filename;

                            $real_base = realpath($base_dir);
                            $real_target_dir = realpath(dirname($target_path));

                            if (!$real_base || !$real_target_dir || strpos($real_target_dir, $real_base) !== 0)
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid write path',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // 6. Prevent overwrite
                            if (file_exists($target_path) && !$overwrite)
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'File exists (overwrite not allowed)',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // 7. JSON validation
                            if ($ext === 'json')
                            {
                                json_decode($content, true);
                                if (json_last_error() !== JSON_ERROR_NONE)
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Invalid JSON content',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }
                            }

                            // 8. Write file
                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            $bytes = $wp_filesystem->put_contents($target_path, $content, LOCK_EX);

                            if ($bytes === false)
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to write file',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            aiomatic_log_to_file('Agent wrote file: ' . $target_path);

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Success: File saved as ' . basename($target_path),
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Missing filename or content',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'get_wp_post_data') 
                    {
                        if(isset($tool_call->function->arguments->post_id))
                        {
                            $post_id = $tool_call->function->arguments->post_id;

                            if (empty($post_id)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: No Post ID provided.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $post = get_post($post_id);
                            if (!$post) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Post with ID $post_id not found.",
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $clean_content = wp_strip_all_tags(strip_shortcodes($post->post_content));

                            $final_output = "Post ID: $post_id\n";
                            $final_output .= "Title: {$post->post_title}\n";
                            $final_output .= "Status: {$post->post_status}\n";
                            $final_output .= "Type: {$post->post_type}\n";
                            $final_output .= "Excerpt: {$post->post_excerpt}\n";
                            $final_output .= "--- CONTENT START ---\n";
                            $final_output .= $clean_content;
                            $final_output .= "\n--- CONTENT END ---";

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aiomatic_substr($final_output, 0, 45000),
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'post_id parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'process_and_transform_data') 
                    {
                        if(isset($tool_call->function->arguments->operation) && isset($tool_call->function->arguments->input))
                        {
                            $operation = $tool_call->function->arguments->operation;
                            $input     = $tool_call->function->arguments->input;

                            if (empty($operation) || empty($input)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: operation and input are required.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $decoded = json_decode($input, true);

                            switch ($operation) 
                            {
                                case 'parse_json':

                                    if ($decoded === null) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Invalid JSON.',
                                            'assistant_message' => $as_mes
                                        ]);
                                        continue 2;
                                    }

                                    aiomatic_agent_add_tool_direct_message($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($decoded),
                                        'assistant_message' => $as_mes
                                    ]);
                                    break;

                                case 'stringify_json':

                                    aiomatic_agent_add_tool_direct_message($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($input),
                                        'assistant_message' => $as_mes
                                    ]);
                                    break;

                                case 'list_keys':

                                    if (!is_array($decoded)) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Input must be JSON object or array.',
                                            'assistant_message' => $as_mes
                                        ]);
                                        continue 2;
                                    }

                                    aiomatic_agent_add_tool_direct_message($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => implode(', ', array_keys($decoded)),
                                        'assistant_message' => $as_mes
                                    ]);
                                    break;

                                case 'extract_field':

                                    if(!isset($tool_call->function->arguments->field))
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: field parameter required.',
                                            'assistant_message' => $as_mes
                                        ]);
                                        continue 2;
                                    }

                                    $field = $tool_call->function->arguments->field;

                                    if (!is_array($decoded)) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Input must be JSON.',
                                            'assistant_message' => $as_mes
                                        ]);
                                        continue 2;
                                    }

                                    if (isset($decoded[$field])) 
                                    {
                                        aiomatic_agent_add_tool_direct_message($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => json_encode($decoded[$field]),
                                            'assistant_message' => $as_mes
                                        ]);
                                    }
                                    else
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: field not found.',
                                            'assistant_message' => $as_mes
                                        ]);
                                    }
                                    break;

                                case 'filter_equals':

                                    if(!isset($tool_call->function->arguments->field))
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: field parameter required.',
                                            'assistant_message' => $as_mes
                                        ]);
                                        continue 2;
                                    }

                                    $field = $tool_call->function->arguments->field;
                                    $value = $tool_call->function->arguments->value ?? '';

                                    if (!is_array($decoded)) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, [
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Input must be JSON array.',
                                            'assistant_message' => $as_mes
                                        ]);
                                        continue 2;
                                    }

                                    $filtered = [];

                                    foreach ($decoded as $item) 
                                    {
                                        if (is_array($item) && isset($item[$field]) && (string)$item[$field] === (string)$value) 
                                        {
                                            $filtered[] = $item;
                                        }
                                    }

                                    aiomatic_agent_add_tool_direct_message($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($filtered),
                                        'assistant_message' => $as_mes
                                    ]);
                                    break;

                                default:

                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: Unknown operation.',
                                        'assistant_message' => $as_mes
                                    ]);
                                    break;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'operation or input parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'pause_execution') 
                    {
                        if(isset($tool_call->function->arguments->seconds))
                        {
                            $seconds = (int)$tool_call->function->arguments->seconds;

                            if ($seconds <= 0) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: seconds must be greater than 0.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // safety cap
                            if ($seconds > 30) 
                            {
                                $seconds = 30;
                            }

                            sleep($seconds);

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Waited $seconds seconds.",
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'seconds parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'wp_validate_post_state') 
                    {
                        if(isset($tool_call->function->arguments->post_id) && isset($tool_call->function->arguments->checks))
                        {
                            $post_id = $tool_call->function->arguments->post_id;
                            $checks  = $tool_call->function->arguments->checks;

                            if (empty($post_id)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: post_id is required.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            if (!is_array($checks) || empty($checks)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: checks must be a non-empty array.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $post = get_post($post_id);

                            $results = [];
                            $all_passed = true;

                            if (in_array('exists', $checks, true)) 
                            {
                                if ($post) {
                                    $results[] = "exists: PASS";
                                } else {
                                    $results[] = "exists: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (!$post) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => implode("\n", $results),
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            if (in_array('has_excerpt', $checks, true)) 
                            {
                                if (!empty($post->post_excerpt)) {
                                    $results[] = "has_excerpt: PASS";
                                } else {
                                    $results[] = "has_excerpt: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('has_featured_image', $checks, true)) 
                            {
                                if (get_post_thumbnail_id($post_id)) {
                                    $results[] = "has_featured_image: PASS";
                                } else {
                                    $results[] = "has_featured_image: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('has_content', $checks, true)) 
                            {
                                $clean = trim(wp_strip_all_tags($post->post_content));
                                if (!empty($clean)) {
                                    $results[] = "has_content: PASS";
                                } else {
                                    $results[] = "has_content: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('content_length', $checks, true)) 
                            {
                                $min = isset($tool_call->function->arguments->min_content_length) ? (int)$tool_call->function->arguments->min_content_length : 100;
                                $len = strlen(wp_strip_all_tags($post->post_content));

                                if ($len >= $min) {
                                    $results[] = "content_length($len >= $min): PASS";
                                } else {
                                    $results[] = "content_length($len < $min): FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('status', $checks, true)) 
                            {
                                $expected = $tool_call->function->arguments->expected_status ?? '';
                                if (!empty($expected) && $post->post_status === $expected) {
                                    $results[] = "status({$post->post_status}): PASS";
                                } else {
                                    $results[] = "status({$post->post_status}): FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('has_terms', $checks, true)) 
                            {
                                $taxonomy = $tool_call->function->arguments->taxonomy ?? '';

                                if (empty($taxonomy)) 
                                {
                                    $results[] = "has_terms: FAIL (taxonomy missing)";
                                    $all_passed = false;
                                } 
                                else 
                                {
                                    $terms = get_the_terms($post_id, $taxonomy);
                                    if (!empty($terms) && !is_wp_error($terms)) {
                                        $results[] = "has_terms($taxonomy): PASS";
                                    } else {
                                        $results[] = "has_terms($taxonomy): FAIL";
                                        $all_passed = false;
                                    }
                                }
                            }

                            $summary = $all_passed ? "ALL CHECKS PASSED" : "SOME CHECKS FAILED";
                            $output = $summary . "\n\n" . implode("\n", $results);

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $output,
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'post_id or checks parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'wp_taxonomy_discovery') 
                    {
                        if(isset($tool_call->function->arguments->operation))
                        {
                            $operation = $tool_call->function->arguments->operation;

                            if (empty($operation)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: operation parameter was not provided.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            if (!in_array($operation, ['list_taxonomies','list_terms','get_post_terms','create_term','set_post_terms'], true))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: Invalid operation parameter provided.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // =========================
                            // LIST TAXONOMIES
                            // =========================
                            if ($operation === 'list_taxonomies')
                            {
                                $taxonomies = get_taxonomies([], 'objects');

                                if (empty($taxonomies))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No taxonomies found on this site.',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $results = [];

                                foreach ($taxonomies as $taxonomy)
                                {
                                    $results[] = sprintf(
                                        "Name: %s | Label: %s | Public: %s | Hierarchical: %s | Object Types: %s",
                                        $taxonomy->name,
                                        $taxonomy->label,
                                        !empty($taxonomy->public) ? 'yes' : 'no',
                                        !empty($taxonomy->hierarchical) ? 'yes' : 'no',
                                        !empty($taxonomy->object_type) ? implode(',', $taxonomy->object_type) : '-'
                                    );
                                }

                                $output = "Available Taxonomies:\n\n" . implode("\n---\n", $results);

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => aiomatic_substr($output, 0, 45000),
                                    'assistant_message' => $as_mes
                                ]);
                            }

                            // =========================
                            // LIST TERMS
                            // =========================
                            elseif ($operation === 'list_terms')
                            {
                                if(!isset($tool_call->function->arguments->taxonomy))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy parameter not found',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $taxonomy = $tool_call->function->arguments->taxonomy;

                                if (!taxonomy_exists($taxonomy))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "Error: Taxonomy $taxonomy does not exist.",
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $terms = get_terms([
                                    'taxonomy' => $taxonomy,
                                    'hide_empty' => false,
                                    'number' => 20
                                ]);

                                if (is_wp_error($terms) || empty($terms))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "No terms found for taxonomy: $taxonomy",
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $results = [];

                                foreach ($terms as $term)
                                {
                                    $results[] = sprintf(
                                        "ID: %d | Name: %s | Slug: %s | Count: %d",
                                        $term->term_id,
                                        $term->name,
                                        $term->slug,
                                        $term->count
                                    );
                                }

                                $output = "Terms for taxonomy '$taxonomy':\n\n" . implode("\n---\n", $results);

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => aiomatic_substr($output, 0, 45000),
                                    'assistant_message' => $as_mes
                                ]);
                            }

                            // =========================
                            // GET POST TERMS
                            // =========================
                            elseif ($operation === 'get_post_terms')
                            {
                                if(!isset($tool_call->function->arguments->taxonomy) || !isset($tool_call->function->arguments->post_id))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy or post_id parameter missing',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $taxonomy = $tool_call->function->arguments->taxonomy;
                                $post_id  = $tool_call->function->arguments->post_id;

                                $terms = get_the_terms($post_id, $taxonomy);

                                if (empty($terms) || is_wp_error($terms))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "No terms assigned.",
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $results = [];

                                foreach ($terms as $term)
                                {
                                    $results[] = sprintf(
                                        "ID: %d | Name: %s | Slug: %s",
                                        $term->term_id,
                                        $term->name,
                                        $term->slug
                                    );
                                }

                                $output = implode("\n", $results);

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $output,
                                    'assistant_message' => $as_mes
                                ]);
                            }

                            // =========================
                            // CREATE TERM
                            // =========================
                            elseif ($operation === 'create_term')
                            {
                                if(!isset($tool_call->function->arguments->taxonomy) || !isset($tool_call->function->arguments->term_name))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy or term_name missing',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $taxonomy = $tool_call->function->arguments->taxonomy;
                                $term_name = $tool_call->function->arguments->term_name;

                                $existing = term_exists($term_name, $taxonomy);

                                if ($existing)
                                {
                                    $term_id = is_array($existing) ? $existing['term_id'] : $existing;

                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "Term already exists. ID: $term_id",
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $created = wp_insert_term($term_name, $taxonomy);

                                if (is_wp_error($created))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => $created->get_error_message(),
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Created term ID: " . $created['term_id'],
                                    'assistant_message' => $as_mes
                                ]);
                            }
                            elseif ($operation === 'set_post_terms')
                            {
                                if (
                                    !isset($tool_call->function->arguments->taxonomy) ||
                                    !isset($tool_call->function->arguments->post_id) ||
                                    !isset($tool_call->function->arguments->term_name)
                                )
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy, post_id or term_name missing',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $taxonomy = sanitize_text_field($tool_call->function->arguments->taxonomy);
                                $post_id  = intval($tool_call->function->arguments->post_id);
                                $terms    = sanitize_text_field($tool_call->function->arguments->term_name);

                                if (empty($taxonomy) || $post_id <= 0 || empty($terms))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Invalid taxonomy, post_id or term_name',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                if (!taxonomy_exists($taxonomy))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "Taxonomy $taxonomy does not exist",
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $term_names = array_map('trim', explode(',', $terms));
                                $term_ids   = [];

                                foreach ($term_names as $name)
                                {
                                    if ($name === '') continue;

                                    $existing = term_exists($name, $taxonomy);

                                    if (!$existing)
                                    {
                                        $created = wp_insert_term($name, $taxonomy);

                                        if (is_wp_error($created))
                                        {
                                            continue;
                                        }

                                        $term_ids[] = (int)$created['term_id'];
                                    }
                                    else
                                    {
                                        $term_ids[] = is_array($existing) ? (int)$existing['term_id'] : (int)$existing;
                                    }
                                }

                                if (empty($term_ids))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "No valid terms to assign",
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                wp_set_post_terms($post_id, $term_ids, $taxonomy, false);

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Success: Assigned " . count($term_ids) . " terms to post $post_id",
                                    'assistant_message' => $as_mes
                                ]);
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'operation parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'get_environment_info') 
                    {
                        if(isset($tool_call->function->arguments->info_type))
                        {
                            $type = sanitize_text_field($tool_call->function->arguments->info_type);

                            $allowed = ['general','plugins','theme','stats','capabilities','post_types','taxonomies','all'];

                            if (!in_array($type, $allowed, true)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: Invalid info_type parameter.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $output = '';

                            if ($type === 'general' || $type === 'all') 
                            {
                                $output .= "--- GENERAL ---\n";
                                $output .= "Site URL: " . site_url() . "\n";
                                $output .= "Home URL: " . home_url() . "\n";
                                $output .= "Name: " . get_bloginfo('name') . "\n";
                                $output .= "Description: " . get_bloginfo('description') . "\n";
                                $output .= "Admin Email: " . get_bloginfo('admin_email') . "\n";
                                $output .= "Language: " . get_bloginfo('language') . "\n";
                                $output .= "WP Version: " . get_bloginfo('version') . "\n\n";
                            }

                            if ($type === 'theme' || $type === 'all') 
                            {
                                $theme = wp_get_theme();

                                $output .= "--- THEME ---\n";
                                $output .= "Name: " . $theme->get('Name') . "\n";
                                $output .= "Version: " . $theme->get('Version') . "\n";
                                $output .= "Author: " . $theme->get('Author') . "\n\n";
                            }

                            if ($type === 'plugins' || $type === 'all' || $type === 'capabilities') 
                            {
                                if (!function_exists('get_plugins')) {
                                    require_once ABSPATH . 'wp-admin/includes/plugin.php';
                                }

                                $active_plugins = get_option('active_plugins', []);
                                $all_plugins = get_plugins();

                                if ($type === 'plugins' || $type === 'all') 
                                {
                                    $output .= "--- ACTIVE PLUGINS ---\n";

                                    if (!empty($active_plugins)) {
                                        foreach ($active_plugins as $plugin_file) {
                                            if (isset($all_plugins[$plugin_file])) {
                                                $output .= "- " . $all_plugins[$plugin_file]['Name'] . " (v" . $all_plugins[$plugin_file]['Version'] . ")\n";
                                            }
                                        }
                                    } else {
                                        $output .= "No active plugins found.\n";
                                    }

                                    $output .= "\n";
                                }
                            }

                            if ($type === 'stats' || $type === 'all') 
                            {
                                $posts    = (int)(wp_count_posts('post')->publish ?? 0);
                                $pages    = (int)(wp_count_posts('page')->publish ?? 0);
                                $products = post_type_exists('product') ? (int)(wp_count_posts('product')->publish ?? 0) : 0;
                                $users    = (int)(count_users()['total_users'] ?? 0);

                                $output .= "--- STATS ---\n";
                                $output .= "Posts: $posts\n";
                                $output .= "Pages: $pages\n";
                                $output .= "Products: $products\n";
                                $output .= "Users: $users\n\n";
                            }

                            if ($type === 'post_types' || $type === 'all') 
                            {
                                $cpts = get_post_types(['public' => true], 'objects');

                                $output .= "--- POST TYPES ---\n";
                                foreach ($cpts as $pt) {
                                    $output .= "- {$pt->name} ({$pt->label})\n";
                                }
                                $output .= "\n";
                            }

                            if ($type === 'taxonomies' || $type === 'all') 
                            {
                                $taxes = get_taxonomies(['public' => true], 'objects');

                                $output .= "--- TAXONOMIES ---\n";
                                foreach ($taxes as $tx) {
                                    $output .= "- {$tx->name} ({$tx->label}) | used on: " . implode(',', $tx->object_type) . "\n";
                                }
                                $output .= "\n";
                            }

                            if ($type === 'capabilities' || $type === 'all') 
                            {
                                $output .= "--- CAPABILITIES ---\n";

                                $output .= "WooCommerce: " . (class_exists('WooCommerce') ? 'yes' : 'no') . "\n";
                                $output .= "Elementor: " . (defined('ELEMENTOR_VERSION') ? 'yes' : 'no') . "\n";
                                $output .= "Gutenberg: " . (function_exists('register_block_type') ? 'yes' : 'no') . "\n";
                                $output .= "REST API: " . (function_exists('register_rest_route') ? 'yes' : 'no') . "\n";

                                $output .= "ACF: " . (class_exists('ACF') ? 'yes' : 'no') . "\n";
                                $output .= "Custom Fields: " . (post_type_supports('post', 'custom-fields') ? 'yes' : 'no') . "\n";
                                $output .= "Featured Images: " . (current_theme_supports('post-thumbnails') ? 'yes' : 'no') . "\n";

                                $output .= "SEO Plugins:\n";
                                $output .= "- Yoast: " . (defined('WPSEO_VERSION') ? 'yes' : 'no') . "\n";
                                $output .= "- RankMath: " . (defined('RANK_MATH_VERSION') ? 'yes' : 'no') . "\n";
                                $output .= "- AIOSEO: " . (defined('AIOSEO_VERSION') ? 'yes' : 'no') . "\n";

                                $output .= "\n";
                            }

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aiomatic_substr(trim($output), 0, 45000),
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'info_type parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'manage_wp_post') 
                    {
                        if (isset($tool_call->function->arguments->operation))
                        {
                            $args = $tool_call->function->arguments;
                            $operation = sanitize_text_field($args->operation);

                            $allowed_operations = array(
                                'create',
                                'update',
                                'trash',
                                'untrash',
                                'delete',
                                'duplicate',
                                'append_content',
                                'prepend_content',
                                'set_featured_image',
                                'delete_featured_image',
                                'set_meta',
                                'delete_meta',
                                'set_terms'
                            );

                            if (!in_array($operation, $allowed_operations, true))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: Invalid operation. Allowed: ' . implode(', ', $allowed_operations),
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // CREATE stays single
                            if ($operation === 'create')
                            {
                                if (!isset($args->post_title) || !isset($args->post_content) || empty($args->post_title) || empty($args->post_content))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: post_title and post_content are required.',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $post_data = [
                                    'post_title'      => wp_strip_all_tags($args->post_title),
                                    'post_content'    => $args->post_content,
                                    'post_status'     => $args->post_status ?? 'draft',
                                    'post_type'       => $args->post_type ?? 'post',
                                    'post_excerpt'    => $args->post_excerpt ?? '',
                                    'post_name'       => isset($args->post_name) ? sanitize_title($args->post_name) : '',
                                    'post_parent'     => isset($args->post_parent) ? intval($args->post_parent) : 0,
                                    'menu_order'      => isset($args->menu_order) ? intval($args->menu_order) : 0,
                                    'comment_status'  => $args->comment_status ?? 'closed',
                                    'ping_status'     => $args->ping_status ?? 'closed',
                                ];

                                $new_post_id = wp_insert_post($post_data, true);

                                if (is_wp_error($new_post_id))
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: ' . $new_post_id->get_error_message(),
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                if (!empty($args->featured_image_id))
                                {
                                    set_post_thumbnail($new_post_id, intval($args->featured_image_id));
                                }

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Success: Post created. ID: $new_post_id. URL: " . get_permalink($new_post_id),
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            // Normalize IDs (THIS is the upgrade)
                            $post_ids = [];

                            if (!empty($args->post_ids))
                            {
                                $post_ids = array_map('intval', array_filter(array_map('trim', explode(',', $args->post_ids))));
                            }
                            elseif (!empty($args->ID))
                            {
                                $post_ids = [intval($args->ID)];
                            }

                            if (empty($post_ids))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: ID or post_ids required.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $results = [];

                            foreach ($post_ids as $post_id)
                            {
                                $existing_post = get_post($post_id);

                                if (!$existing_post)
                                {
                                    $results[] = "Error: Post $post_id not found.";
                                    continue;
                                }

                                // --- operations ---

                                if ($operation === 'update')
                                {
                                    $post_data = ['ID' => $post_id];

                                    if (isset($args->post_title)) $post_data['post_title'] = wp_strip_all_tags($args->post_title);
                                    if (isset($args->post_content)) $post_data['post_content'] = $args->post_content;
                                    if (isset($args->post_status)) $post_data['post_status'] = $args->post_status;
                                    if (isset($args->post_type)) $post_data['post_type'] = $args->post_type;
                                    if (isset($args->post_excerpt)) $post_data['post_excerpt'] = $args->post_excerpt;
                                    if (isset($args->post_name)) $post_data['post_name'] = sanitize_title($args->post_name);
                                    if (isset($args->post_parent)) $post_data['post_parent'] = intval($args->post_parent);
                                    if (isset($args->menu_order)) $post_data['menu_order'] = intval($args->menu_order);
                                    if (isset($args->comment_status)) $post_data['comment_status'] = $args->comment_status;
                                    if (isset($args->ping_status)) $post_data['ping_status'] = $args->ping_status;

                                    $updated_post_id = wp_update_post($post_data, true);

                                    if (is_wp_error($updated_post_id))
                                    {
                                        $results[] = "Error update $post_id: " . $updated_post_id->get_error_message();
                                        continue;
                                    }

                                    if (isset($args->featured_image_id))
                                    {
                                        $fid = intval($args->featured_image_id);
                                        $fid > 0 ? set_post_thumbnail($post_id, $fid) : delete_post_thumbnail($post_id);
                                    }

                                    $results[] = "Updated $post_id";
                                }
                                elseif ($operation === 'trash')
                                {
                                    $results[] = wp_trash_post($post_id) ? "Trashed $post_id" : "Error trash $post_id";
                                }
                                elseif ($operation === 'untrash')
                                {
                                    $results[] = wp_untrash_post($post_id) ? "Restored $post_id" : "Error restore $post_id";
                                }
                                elseif ($operation === 'delete')
                                {
                                    $results[] = wp_delete_post($post_id, true) ? "Deleted $post_id" : "Error delete $post_id";
                                }
                                elseif ($operation === 'duplicate')
                                {
                                    $new_post = [
                                        'post_title' => $existing_post->post_title . ' (Copy)',
                                        'post_content' => $existing_post->post_content,
                                        'post_excerpt' => $existing_post->post_excerpt,
                                        'post_status' => 'draft',
                                        'post_type' => $existing_post->post_type,
                                    ];

                                    $new_id = wp_insert_post($new_post, true);

                                    if (is_wp_error($new_id))
                                    {
                                        $results[] = "Error duplicate $post_id";
                                        continue;
                                    }

                                    $results[] = "Duplicated $post_id → $new_id";
                                }
                                elseif ($operation === 'append_content')
                                {
                                    if (empty($args->post_content))
                                    {
                                        $results[] = "Error: missing content for $post_id";
                                        continue;
                                    }

                                    wp_update_post([
                                        'ID' => $post_id,
                                        'post_content' => $existing_post->post_content . $args->post_content
                                    ]);

                                    $results[] = "Appended $post_id";
                                }
                                elseif ($operation === 'prepend_content')
                                {
                                    if (empty($args->post_content))
                                    {
                                        $results[] = "Error: missing content for $post_id";
                                        continue;
                                    }

                                    wp_update_post([
                                        'ID' => $post_id,
                                        'post_content' => $args->post_content . $existing_post->post_content
                                    ]);

                                    $results[] = "Prepended $post_id";
                                }
                                elseif ($operation === 'set_featured_image')
                                {
                                    $fid = intval($args->featured_image_id ?? 0);
                                    $image_url = isset($args->image_url) ? trim($args->image_url) : '';

                                    if ($fid <= 0 && !empty($image_url)) {

                                        require_once ABSPATH . 'wp-admin/includes/media.php';
                                        require_once ABSPATH . 'wp-admin/includes/file.php';
                                        require_once ABSPATH . 'wp-admin/includes/image.php';

                                        $sideloaded = media_sideload_image($image_url, $post_id, null, 'id');

                                        if (is_wp_error($sideloaded)) {
                                            $results[] = "Error featured $post_id: " . $sideloaded->get_error_message();
                                            return;
                                        }

                                        $fid = (int) $sideloaded;
                                    }

                                    if ($fid <= 0) {
                                        $results[] = "Error featured $post_id: missing image";
                                        return;
                                    }

                                    $results[] = set_post_thumbnail($post_id, $fid)
                                        ? "Featured set $post_id ($fid)"
                                        : "Error featured $post_id";
                                }
                                elseif ($operation === 'delete_featured_image')
                                {
                                    delete_post_thumbnail($post_id);
                                    $results[] = "Removed featured $post_id";
                                }
                                elseif ($operation === 'set_meta')
                                {
                                    if (empty($args->meta_key))
                                    {
                                        $results[] = "Error meta_key $post_id";
                                        continue;
                                    }

                                    update_post_meta($post_id, sanitize_key($args->meta_key), $args->meta_value ?? '');
                                    $results[] = "Meta set $post_id";
                                }
                                elseif ($operation === 'delete_meta')
                                {
                                    if (empty($args->meta_key))
                                    {
                                        $results[] = "Error meta_key $post_id";
                                        continue;
                                    }

                                    delete_post_meta($post_id, sanitize_key($args->meta_key));
                                    $results[] = "Meta deleted $post_id";
                                }
                                elseif ($operation === 'set_terms')
                                {
                                    $taxonomy = sanitize_key($args->taxonomy ?? '');
                                    $terms_raw = $args->terms ?? '';

                                    $terms = array_map('intval', array_filter(array_map('trim', explode(',', $terms_raw))));

                                    if (!$taxonomy || empty($terms))
                                    {
                                        $results[] = "Error terms $post_id";
                                        continue;
                                    }

                                    wp_set_object_terms($post_id, $terms, $taxonomy, false);
                                    $results[] = "Terms set $post_id";
                                }
                            }

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => implode("\n", $results),
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'operation parameter missing',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'search_site_posts') 
                    {
                        if(isset($tool_call->function->arguments))
                        {
                            $args_in = $tool_call->function->arguments;

                            $query_str   = isset($args_in->query) ? $args_in->query : '';
                            $post_type   = !empty($args_in->post_type) ? (array)$args_in->post_type : ['post','page'];
                            $post_status = !empty($args_in->post_status) ? sanitize_text_field($args_in->post_status) : 'any';
                            $limit       = !empty($args_in->posts_per_page) ? min((int)$args_in->posts_per_page, 20) : 5;
                            $offset      = !empty($args_in->offset) ? max((int)$args_in->offset, 0) : 0;

                            $args = [
                                'post_type'      => $post_type,
                                'post_status'    => $post_status,
                                'posts_per_page' => $limit,
                                'offset'         => $offset,
                                'orderby'        => 'date',
                                'order'          => 'DESC',
                                'no_found_rows'  => true
                            ];

                            // keyword
                            if (!empty($query_str)) {
                                $args['s'] = sanitize_text_field($query_str);
                                $args['orderby'] = 'relevance';
                            }

                            // sorting
                            if (!empty($args_in->orderby)) {
                                $args['orderby'] = sanitize_text_field($args_in->orderby);
                            }
                            if (!empty($args_in->order)) {
                                $args['order'] = strtoupper($args_in->order) === 'ASC' ? 'ASC' : 'DESC';
                            }
                            if (!empty($args_in->meta_key)) {
                                $args['meta_key'] = sanitize_text_field($args_in->meta_key);
                            }

                            // author
                            if (!empty($args_in->author_id)) {
                                $args['author'] = (int)$args_in->author_id;
                            }

                            // date (FIXED structure)
                            if (!empty($args_in->date_after) || !empty($args_in->date_before)) {
                                $date_query = [];

                                if (!empty($args_in->date_after)) {
                                    $date_query['after'] = sanitize_text_field($args_in->date_after);
                                }
                                if (!empty($args_in->date_before)) {
                                    $date_query['before'] = sanitize_text_field($args_in->date_before);
                                }

                                $date_query['inclusive'] = true;
                                $args['date_query'] = [$date_query];
                            }

                            // taxonomy
                            if (!empty($args_in->taxonomy) && !empty($args_in->terms)) {
                                $terms = array_map('intval', explode(',', $args_in->terms));

                                $args['tax_query'] = [
                                    [
                                        'taxonomy' => sanitize_text_field($args_in->taxonomy),
                                        'field'    => 'term_id',
                                        'terms'    => $terms
                                    ]
                                ];
                            }

                            // meta
                            $meta_query = ['relation' => 'AND'];

                            if (isset($args_in->has_featured_image)) {
                                if ($args_in->has_featured_image === 'yes') {
                                    $meta_query[] = [
                                        'key'     => '_thumbnail_id',
                                        'compare' => 'EXISTS'
                                    ];
                                } elseif ($args_in->has_featured_image === 'no') {
                                    $meta_query[] = [
                                        'relation' => 'OR',
                                        [
                                            'key'     => '_thumbnail_id',
                                            'compare' => 'NOT EXISTS'
                                        ],
                                        [
                                            'key'     => '_thumbnail_id',
                                            'value'   => '',
                                            'compare' => '='
                                        ]
                                    ];
                                }
                            }

                            // meta filters
                            if (!empty($args_in->meta_filters) && is_string($args_in->meta_filters)) {
                                $filters = explode('|', $args_in->meta_filters);
                                $count = 0;

                                foreach ($filters as $raw_filter) {
                                    if ($count >= 5) break;

                                    $parts = array_map('trim', explode(':', trim($raw_filter)));

                                    $key     = $parts[0] ?? '';
                                    $value   = $parts[1] ?? '';
                                    $compare = strtoupper($parts[2] ?? '=');

                                    $allowed = ['=', '!=', '>', '>=', '<', '<=', 'LIKE', 'EXISTS', 'NOT EXISTS'];
                                    if (!in_array($compare, $allowed, true)) {
                                        $compare = '=';
                                    }

                                    if ($key === '') continue;

                                    if ($compare === 'EXISTS' || $compare === 'NOT EXISTS') {
                                        $meta_query[] = [
                                            'key'     => sanitize_text_field($key),
                                            'compare' => $compare
                                        ];
                                    } else {
                                        $meta_query[] = [
                                            'key'     => sanitize_text_field($key),
                                            'value'   => sanitize_text_field($value),
                                            'compare' => $compare
                                        ];
                                    }

                                    $count++;
                                }
                            }

                            if (count($meta_query) > 1) {
                                $args['meta_query'] = $meta_query;
                            }
                            
                            $has_excerpt_filter = null;
                            $excerpt_filter_cb  = null;

                            if (isset($args_in->has_excerpt)) {
                                if ($args_in->has_excerpt === 'yes') {
                                    $has_excerpt_filter = 'yes';
                                } elseif ($args_in->has_excerpt === 'no') {
                                    $has_excerpt_filter = 'no';
                                }
                            }

                            $length_filter_cb = null;

                            $min_len = isset($args_in->min_content_length) ? (int)$args_in->min_content_length : 0;
                            $max_len = isset($args_in->max_content_length) && (int)$args_in->max_content_length > 0
                                ? (int)$args_in->max_content_length
                                : 0;

                            if ($has_excerpt_filter !== null) {

                                $excerpt_filter_cb = function ($where) use ($has_excerpt_filter) {
                                    global $wpdb;

                                    if ($has_excerpt_filter === 'yes') {
                                        $where .= " AND {$wpdb->posts}.post_excerpt != ''";
                                    } elseif ($has_excerpt_filter === 'no') {
                                        $where .= " AND ({$wpdb->posts}.post_excerpt = '' OR {$wpdb->posts}.post_excerpt IS NULL)";
                                    }

                                    return $where;
                                };

                                add_filter('posts_where', $excerpt_filter_cb);
                            }
                            if ($min_len > 0 || $max_len > 0) {

                                $length_filter_cb = function ($where) use ($min_len, $max_len) {
                                    global $wpdb;

                                    if ($min_len > 0) {
                                        $where .= $wpdb->prepare(
                                            " AND CHAR_LENGTH({$wpdb->posts}.post_content) >= %d",
                                            $min_len
                                        );
                                    }

                                    if ($max_len > 0) {
                                        $where .= $wpdb->prepare(
                                            " AND CHAR_LENGTH({$wpdb->posts}.post_content) <= %d",
                                            $max_len
                                        );
                                    }

                                    return $where;
                                };

                                add_filter('posts_where', $length_filter_cb);
                            }
                            $query = new WP_Query($args);
                            
                            if ($excerpt_filter_cb !== null) {
                                remove_filter('posts_where', $excerpt_filter_cb);
                            }
                            if ($length_filter_cb !== null) {
                                remove_filter('posts_where', $length_filter_cb);
                            }
                            $results = [];

                            if ($query->have_posts()) 
                            {
                                foreach ($query->posts as $post) 
                                {
                                    $content = wp_strip_all_tags($post->post_content);
                                    $results[] = sprintf(
                                        "ID: %d | Title: %s | Status: %s | Date: %s | Words: %d | Image: %s | Excerpt: %s",
                                        $post->ID,
                                        $post->post_title,
                                        $post->post_status,
                                        $post->post_date,
                                        str_word_count($content),
                                        has_post_thumbnail($post->ID) ? 'yes' : 'no',
                                        !empty($post->post_excerpt) ? 'yes' : 'no'
                                    );
                                }

                                wp_reset_postdata();
                            }

                            if (empty($results)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "No results found for the given filters.",
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            $output = "Filtered Search Results:\n\n" . implode("\n---\n", $results);

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aiomatic_substr($output, 0, 30000),
                                'assistant_message' => $as_mes
                            ]);
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'arguments not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'wp_sideload_media') 
                    {
                        if(isset($tool_call->function->arguments->image_url))
                        {
                            $image_url = $tool_call->function->arguments->image_url;
                            $post_id = $tool_call->function->arguments->post_id ?? 0;

                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: No image URL provided.',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            require_once(ABSPATH . 'wp-admin/includes/media.php');
                            require_once(ABSPATH . 'wp-admin/includes/file.php');
                            require_once(ABSPATH . 'wp-admin/includes/image.php');

                            $result = media_sideload_image($image_url, $post_id, "AIomatic", 'id');

                            if (is_wp_error($result)) 
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result->get_error_message(),
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }

                            aiomatic_agent_add_tool_direct_message($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Attachment ID: $result | URL: " . wp_get_attachment_url($result),
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'get_wp_media_info') 
                    {
                        $args = $tool_call->function->arguments ?? null;

                        if ($args && (isset($args->post_id) || isset($args->attachment_id)))
                        {
                            $post_id       = isset($args->post_id) ? intval($args->post_id) : 0;
                            $attachment_id = isset($args->attachment_id) ? intval($args->attachment_id) : 0;
                            $include_att   = isset($args->include_attachments) ? (bool)$args->include_attachments : false;

                            $output = [];

                            // =========================
                            // ATTACHMENT MODE
                            // =========================
                            if ($attachment_id > 0)
                            {
                                $attachment = get_post($attachment_id);

                                if (!$attachment || $attachment->post_type !== 'attachment')
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: Attachment not found.',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $file_path = get_attached_file($attachment_id);
                                $file_url  = wp_get_attachment_url($attachment_id);
                                $metadata  = wp_get_attachment_metadata($attachment_id);

                                $output[] = "Attachment ID: $attachment_id";
                                $output[] = "URL: $file_url";
                                $output[] = "Mime: {$attachment->post_mime_type}";
                                $output[] = "File: $file_path";

                                if (!empty($metadata['width']) && !empty($metadata['height']))
                                {
                                    $output[] = "Dimensions: {$metadata['width']}x{$metadata['height']}";
                                }

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => implode("\n", $output),
                                    'assistant_message' => $as_mes
                                ]);

                                continue;
                            }

                            // =========================
                            // POST MODE
                            // =========================
                            if ($post_id > 0)
                            {
                                $post = get_post($post_id);

                                if (!$post)
                                {
                                    aiomatic_agent_add_tool_results($reply, [
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: Post not found.',
                                        'assistant_message' => $as_mes
                                    ]);
                                    continue;
                                }

                                $output[] = "Post ID: $post_id";
                                $output[] = "Title: {$post->post_title}";

                                // Featured image
                                $thumb_id = get_post_thumbnail_id($post_id);

                                if ($thumb_id)
                                {
                                    $thumb_url = wp_get_attachment_url($thumb_id);
                                    $meta      = wp_get_attachment_metadata($thumb_id);

                                    $output[] = "Featured Image: YES";
                                    $output[] = "Featured Image ID: $thumb_id";
                                    $output[] = "Featured Image URL: $thumb_url";

                                    if (!empty($meta['width']) && !empty($meta['height']))
                                    {
                                        $output[] = "Featured Image Size: {$meta['width']}x{$meta['height']}";
                                    }
                                }
                                else
                                {
                                    $output[] = "Featured Image: NO";
                                }

                                // Attachments
                                if ($include_att)
                                {
                                    $attachments = get_children([
                                        'post_parent' => $post_id,
                                        'post_type'   => 'attachment',
                                        'numberposts' => 10
                                    ]);

                                    if (!empty($attachments))
                                    {
                                        $output[] = "--- Attachments ---";

                                        foreach ($attachments as $att)
                                        {
                                            $att_id  = $att->ID;
                                            $att_url = wp_get_attachment_url($att_id);
                                            $meta    = wp_get_attachment_metadata($att_id);

                                            $line = "ID: $att_id | Type: {$att->post_mime_type} | URL: $att_url";

                                            if (!empty($meta['width']) && !empty($meta['height']))
                                            {
                                                $line .= " | {$meta['width']}x{$meta['height']}";
                                            }

                                            $output[] = $line;
                                        }
                                    }
                                    else
                                    {
                                        $output[] = "Attachments: none";
                                    }
                                }

                                aiomatic_agent_add_tool_direct_message($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => implode("\n", $output),
                                    'assistant_message' => $as_mes
                                ]);
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, [
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'post_id or attachment_id parameter not found',
                                'assistant_message' => $as_mes
                            ]);
                        }
                    }
                    elseif ($tool_call->function->name === 'query_toubiz_events') 
                    {
                        if (!function_exists('is_plugin_active')) 
                        {
                            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                        }
                        $plugin_active = is_plugin_active('aiomatic-extension-toubiz-api/aiomatic-extension-toubiz-api.php');
                        if (!$plugin_active) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Required plugin (Aimogen Extension Toubiz API) not activated.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }
                        if (!function_exists('aiomatic_get_toubiz_api_results')) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Required plugin (Aimogen Extension Toubiz API) not correctly installed.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }
                        $search = '';
                        if(isset($tool_call->function->arguments['search']))
                        {
                            $search = $tool_call->function->arguments['search'];
                        }
                        $date_after = '';
                        if(isset($tool_call->function->arguments['date_after']))
                        {
                            $date_after = $tool_call->function->arguments['date_after'];
                        }
                        $date_before = '';
                        if(isset($tool_call->function->arguments['date_before']))
                        {
                            $date_before = $tool_call->function->arguments['date_before'];
                        }
                        $type = '';
                        if(isset($tool_call->function->arguments['type']))
                        {
                            $type = $tool_call->function->arguments['type'];
                        }
                        $event_type = '';
                        if(isset($tool_call->function->arguments['event_type']))
                        {
                            $event_type = $tool_call->function->arguments['event_type'];
                        }
                        $rectangle_area = '';
                        if(isset($tool_call->function->arguments['rectangle_area']))
                        {
                            $rectangle_area = $tool_call->function->arguments['rectangle_area'];
                        }
                        $distance_from = '';
                        if(isset($tool_call->function->arguments['distance_from']))
                        {
                            $distance_from = $tool_call->function->arguments['distance_from'];
                        }
                        $languages = '';
                        if(isset($tool_call->function->arguments['languages']))
                        {
                            $languages = $tool_call->function->arguments['languages'];
                        }
                        $toubiz_data = aiomatic_get_toubiz_api_results($search, $date_after, $date_before, $type, $event_type, $rectangle_area, $distance_from, $languages);
                        if ($toubiz_data === false) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Failed to access Toubiz API',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to access Toubiz API: ' . print_r($tool_call->function->arguments, true));
                        } 
                        else 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $toubiz_data,
                                'assistant_message' => $as_mes
                            ));
                        }
                    }
                    elseif ($tool_call->function->name === 'website_scraper') 
                    {
                        if(isset($tool_call->function->arguments->url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $scurl = $tool_call->function->arguments->url;
                            if (empty($scurl) || !filter_var($scurl, FILTER_VALIDATE_URL)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid scrape url provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $parsed = parse_url($scurl);
                            if (!isset($parsed['scheme']) || !in_array(strtolower($parsed['scheme']), ['http', 'https']))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Only http/https URLs are allowed',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            $host = $parsed['host'];
                            $ip = gethostbyname($host);
                            if (
                                $ip === '127.0.0.1' ||
                                str_starts_with($ip, '10.') ||
                                str_starts_with($ip, '192.168.') ||
                                preg_match('/^172\.(1[6-9]|2\d|3[0-1])\./', $ip)
                            ) {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Access to local/internal URLs is not allowed',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['scrape_method']) && trim($aiomatic_Chatbot_Settings['scrape_method']) != '')
                            {
                                $scrape_method = trim($aiomatic_Chatbot_Settings['scrape_method']);
                            }
                            else
                            {
                                $scrape_method = '0';
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_chars']) && trim($aiomatic_Chatbot_Settings['max_chars']) != '')
                            {
                                $max_chars = trim($aiomatic_Chatbot_Settings['max_chars']);
                            }
                            else
                            {
                                $max_chars = '';
                            }
                            $scrape_selector = 'auto';
                            $scrape_string = '';
                            if (isset($aiomatic_Chatbot_Settings['strip_tags']) && trim($aiomatic_Chatbot_Settings['strip_tags']) != '')
                            {
                                $strip_tags = trim($aiomatic_Chatbot_Settings['strip_tags']);
                            }
                            else
                            {
                                $strip_tags = '0';
                            }
                            $scraped_data = aiomatic_scrape_page($scurl, $scrape_method, $scrape_selector, $scrape_string);
                            if($scraped_data === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to scrape website URL: ' . $scurl,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                if($strip_tags == '1')
                                {
                                    $scraped_data = wp_strip_all_tags($scraped_data);
                                }
                                else
                                {
                                    $scraped_data = aiomatic_fix_relative_links($scraped_data, $scurl);
                                }
                                if(!empty($max_chars) && is_numeric($max_chars))
                                {
                                    $scraped_data = (aiomatic_strlen($scraped_data) > intval($max_chars)) ? aiomatic_substr($scraped_data, 0, intval($max_chars)) : $scraped_data;
                                }
                                $scraped_data = aiomatic_substr($scraped_data, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $scraped_data,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'rss_feed_parser') 
                    {
                        if(isset($tool_call->function->arguments->url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $scurl = $tool_call->function->arguments->url;
                            if (empty($scurl)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty RSS feed URL provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_rss_items']) && trim($aiomatic_Chatbot_Settings['max_rss_items']) != '')
                            {
                                $max_rss_items = intval(trim($aiomatic_Chatbot_Settings['max_rss_items']));
                            }
                            else
                            {
                                $max_rss_items = PHP_INT_MAX;
                            }
                            if (isset($aiomatic_Chatbot_Settings['rss_template']) && trim($aiomatic_Chatbot_Settings['rss_template']) != '')
                            {
                                $rss_template = trim($aiomatic_Chatbot_Settings['rss_template']);
                            }
                            else
                            {
                                $rss_template = '[%%item_counter%%]: %%item_title%% - %%item_description%%';
                            }
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to load RSS parser library',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($scurl);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error in parsing RSS feed: ' . $feed->error(),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $final_result = '';
                            $items = $feed->get_items();
                            foreach($items as $itemx)
                            {
                                $post_link = trim($itemx->get_permalink());
                                $post_fcats = $itemx->get_categories();
                                if ($fauthor = $itemx->get_author()) 
                                {
                                    $user_name = $fauthor->get_name();
                                }
                                else
                                {
                                    $user_name = '';
                                }
                                $feed_cats = array();
                                if(is_array($post_fcats))
                                {
                                    foreach($post_fcats as $cata)
                                    {
                                        $feed_cats[] = $cata->__toString();
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                }
                                else
                                {
                                    $post_cats = '';
                                }
                                $post_excerpt = $itemx->get_description();
                                $final_content = $itemx->get_content();
                                $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                            }
                            $template_copy = '';
                            $processed = 0;
                            foreach($rss_feeds as $rtitle => $this_rss)
                            {
                                if(!empty($max_rss_items) && $processed >= $max_rss_items)
                                {
                                    break;
                                }
                                $template_copy = $rss_template;
                                $template_copy = str_replace('%%item_counter%%', $processed + 1, $template_copy);
                                $template_copy = str_replace('%%item_title%%', $rtitle, $template_copy);
                                $template_copy = str_replace('%%item_content%%', $this_rss['content'], $template_copy);
                                $template_copy = str_replace('%%item_description%%', $this_rss['excerpt'], $template_copy);
                                $template_copy = str_replace('%%item_url%%', $this_rss['url'], $template_copy);
                                $template_copy = str_replace('%%item_author%%', $this_rss['author'], $template_copy);
                                $template_copy = str_replace('%%item_categories%%', $this_rss['cats'], $template_copy);
                                if(!empty($template_copy))
                                {
                                    $final_result .= $template_copy . PHP_EOL;
                                }
                                $processed++;
                            }
                            if(empty($final_result))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse RSS URL (no data returned): ' . $scurl,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'google_results_parser') 
                    {
                        if(isset($tool_call->function->arguments->keywords))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $keywords = $tool_call->function->arguments->keywords;
                            if (empty($keywords)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty keywords parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_google_items']) && trim($aiomatic_Chatbot_Settings['max_google_items']) != '')
                            {
                                $max_google_items = intval(trim($aiomatic_Chatbot_Settings['max_google_items']));
                            }
                            else
                            {
                                $max_google_items = PHP_INT_MAX;
                            }
                            if (isset($aiomatic_Chatbot_Settings['google_template']) && trim($aiomatic_Chatbot_Settings['google_template']) != '')
                            {
                                $google_template = trim($aiomatic_Chatbot_Settings['google_template']);
                            }
                            else
                            {
                                $google_template = '[%%item_counter%%]: %%item_title%% - %%item_snippet%%';
                            }
                            $locale = '';
                            if (isset($aiomatic_Main_Settings['internet_gl']) && $aiomatic_Main_Settings['internet_gl'] != '')
                            {
                                $locale = $aiomatic_Main_Settings['internet_gl'];
                            }
                            $internet_rez = aiomatic_internet_result($keywords, true, $locale);
                            $processed = 0;
                            $final_res = '';
                            foreach($internet_rez as $emb)
                            {
                                if(!empty($max_google_items) && $processed >= $max_google_items)
                                {
                                    break;
                                }
                                $template_copy = $google_template;
                                $template_copy = str_replace('%%item_counter%%', $processed + 1, $template_copy);
                                $template_copy = str_replace('%%item_title%%', $emb['title'], $template_copy);
                                $template_copy = str_replace('%%item_snippet%%', $emb['snippet'], $template_copy);
                                $template_copy = str_replace('%%item_url%%', $emb['link'], $template_copy);
                                $final_res .= $template_copy . PHP_EOL;
                                $processed++;
                            }
                            if(empty($final_res))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse Google SERP for keyword (no data returned): ' . $keywords,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $final_res = aiomatic_substr($final_res, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_res,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'keywords parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'royalty_free_image_search') 
                    {
                        if(isset($tool_call->function->arguments->keyword))
                        {
                            $raw_img_list = array();
                            $full_result_list = array();
                            $result = '';
                            $keyword = $tool_call->function->arguments->keyword;
                            $keyword = function_exists('aiomatic_normalize_royalty_free_image_keyword')
                                ? aiomatic_normalize_royalty_free_image_keyword($keyword)
                                : sanitize_text_field(wp_strip_all_tags((string) $keyword));
                            if (empty($keyword)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty keyword parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $temp_img_attr = '';
                            $attached_id = '';
                            $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $keyword, $temp_img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                            if(empty($temp_get_img))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to get royalty free image for keyword: ' . $keyword,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $temp_get_img = aiomatic_sanitize_image_src($temp_get_img);
                                if($temp_get_img !== false)
                                {
                                    aiomatic_agent_add_tool_direct_message($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => '<img class="image_max_w_ai" src="' . $temp_get_img . '">',
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'keyword parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                            continue;
                        }
                    }
                    elseif ($tool_call->function->name === 'query_wp_database') 
                    {
                        if(isset($tool_call->function->arguments->query))
                        {
                            $query = $tool_call->function->arguments->query;
                            if (empty($query)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty query parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            if (isset($aiomatic_Chatbot_Settings['database_command_types']) && is_array($aiomatic_Chatbot_Settings['database_command_types']) && !empty($aiomatic_Chatbot_Settings['database_command_types']))
                            {
                                $allowed_commands = $aiomatic_Chatbot_Settings['database_command_types'];
                            }
                            else
                            {
                                $allowed_commands = array('SELECT');
                            }
                            preg_match('/^\s*(\w+)/i', $query, $matches);
                            $query_type = strtoupper($matches[1] ?? '');
                            if (!in_array($query_type, $allowed_commands, true)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Query type '$query_type' is not allowed. Allowed types: " . implode(', ', $allowed_commands),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            global $wpdb;
                            try 
                            {
                                $lead_result = null;
                                if ($query_type === 'SELECT') 
                                {
                                    $lead_result = $wpdb->get_results($query, ARRAY_A);
                                } 
                                elseif (in_array($query_type, array('INSERT', 'UPDATE', 'DELETE'), true)) 
                                {
                                    $lead_result = $wpdb->query($query); 
                                }
                                if ($lead_result === null || $lead_result === false) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error! Invalid query or no results found.',
                                        'assistant_message' => $as_mes
                                    ));
                                } 
                                else 
                                {
                                    if ($query_type === 'SELECT' && count($lead_result) > 500) {
                                        $lead_result = array_slice($lead_result, 0, 500);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($lead_result), 
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            } 
                            catch (Exception $e) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error executing the query: ' . $e->getMessage(),
                                    'assistant_message' => $as_mes
                                ));
                            }
                            continue;
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                            continue;
                        }
                    }
                    elseif ($tool_call->function->name === 'aimogen_execute_omniblock_rule') 
                    {
                        if(isset($tool_call->function->arguments->omniblock_id))
                        {
                            if(isset($tool_call->function->arguments->input_parameters))
                            {
                                $input_text = $tool_call->function->arguments->input_parameters;
                            }
                            else
                            {
                                $input_text = '';
                            }
                            $omniblock_id = $tool_call->function->arguments->omniblock_id;
                            if (empty($omniblock_id)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty omniblock_id parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            if (isset($aiomatic_Chatbot_Settings['god_omniblock_rules']) && !empty(trim($aiomatic_Chatbot_Settings['god_omniblock_rules'])))
                            {
                                $omniblock_descriptions = array();
                                $omni_arr = preg_split('/\r\n|\r|\n/', trim($aiomatic_Chatbot_Settings['god_omniblock_rules']));
                                $omni_arr = array_map('trim', $omni_arr);
                                $omni_arr = array_filter($omni_arr);
                                foreach ($omni_arr as $line) {
                                    if (strpos($line, '=>') !== false) {
                                        [$id, $desc] = array_map('trim', explode('=>', $line, 2));
                                        if (!empty($id) && !empty($desc)) {
                                            $omniblock_descriptions[$id] = "`$id`: $desc";
                                        }
                                    }
                                }
                                if(!array_key_exists($omniblock_id, $omniblock_descriptions))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'This OmniBlock ID does not exist in the configured rules',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            else
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No OmniBlock rules configured in settings',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $input_text = json_decode($input_text, true);
                            if($input_text === null || $input_text === false || $input_text === true)
                            {
                                $input_text = [];
                            }
                            require_once (dirname(__FILE__) . "/aiomatic-automation.php"); 
                            $cont = 0;
                            $id_parts = explode('_', $omniblock_id);
                            if(!isset($id_parts[1]))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Incorrect OmniBlock ID submitted in request',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(count($id_parts) > 2)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Incorrect format for OmniBlock IDs',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $param = $id_parts[0];
                            $omniTriggerID = $id_parts[1];
                            $rules = get_option('aiomatic_omni_list', array());
                            $found = false;
                            if (!empty($rules)) 
                            {
                                $default_block_types = aimogen_execute_omniblock_rules_default_block_types(); 
                                foreach ($rules as $request => $bundle[]) 
                                {
                                    if ($cont == $param) 
                                    {
                                        $bundle_values    = array_values($bundle);
                                        $myValues         = $bundle_values[$cont];
                                        $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                                        $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                                        $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                                        $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                                        $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                                        $main_keywords    = isset($array_my_values[4]) ? $array_my_values[4] : '';
                                        $title_once       = isset($array_my_values[5]) ? $array_my_values[5] : '';
                                        $rule_description = isset($array_my_values[6]) ? $array_my_values[6] : '';
                                        $rule_unique_id   = isset($array_my_values[7]) ? $array_my_values[7] : '';
                                        $sortable_cards   = isset($array_my_values[8]) ? $array_my_values[8] : '';
                                        $more_keywords    = isset($array_my_values[9]) ? $array_my_values[9] : '';
                                        $days_no_run      = isset($array_my_values[10]) ? $array_my_values[10] : '';
                                        $block_data       = json_decode($sortable_cards, true);
                                        if(!empty($block_data))
                                        {
                                            foreach($block_data as $index => $current_block)
                                            {
                                                $card_type_found = array();
                                                foreach($default_block_types as $def_card)
                                                {
                                                    if($current_block['type'] == $def_card['id'])
                                                    {
                                                        $card_type_found = $def_card;
                                                        break;
                                                    }
                                                }
                                                if(!empty($card_type_found) && $omniTriggerID == $current_block['identifier'] && $current_block['type'] === 'ai_chatbot_omniblock')
                                                {
                                                    $return_last_result = true;
                                                    $return_me = aiomatic_run_rule($cont, 5, 1, 0, null, '', $omniTriggerID, $return_last_result, $input_text);
                                                    if($return_me == 'fail')
                                                    {
                                                        aiomatic_log_to_file('OmniBlock AI Chatbot Trigger rule running failed, rule ID: ' . $param . ' OmniBlock ID: ' . $omniTriggerID);
                                                    }
                                                    aiomatic_agent_add_tool_results($reply, array(
                                                        "tool_call_id" => $tool_call->id,
                                                        "role" => "tool",
                                                        "content" => wp_kses_post($return_me), 
                                                        'assistant_message' => $as_mes
                                                    ));
                                                    $found = true;
                                                    break 2;
                                                }
                                            }
                                        }
                                    }
                                    $cont = $cont + 1;
                                }
                                if($found == false)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Specified \'AI Chatbot Trigger\' OmniBlock ID not found(3): ' . $omniblock_id,
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            } 
                            else 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No rules found for aiomatic_omni_list!',
                                    'assistant_message' => $as_mes
                                ));
                            }
                            continue;
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                            continue;
                        }
                    }
                    elseif ($tool_call->function->name === 'generate_ai_model_reasoning') 
                    {
                        if(isset($tool_call->function->arguments->prompt))
                        {
                            $prompt = $tool_call->function->arguments->prompt;
                            if (empty($prompt)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $model = '';
                            if(isset($tool_call->function->arguments->model))
                            {
                                $model = $tool_call->function->arguments->model;
                            }
                            if (empty($model)) 
                            {
                                $model = AIMOGEN_DEFAULT_MODEL;
                            }
                            if (!isset($aiomatic_Main_Settings['app_id'])) 
                            {
                                $aiomatic_Main_Settings['app_id'] = '';
                            }
                            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
                            $appids = array_filter($appids);
                            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
                            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
                            if (empty($token))
                            {
                                aiomatic_log_to_file('You need to enter an OpenAI API key for this to work!');
                                $result = '[ERROR] API key not configured in plugin settings.';
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $query_token_count = count(aiomatic_encode($prompt));
                            $max_tokens = aimogenpro_get_max_tokens($model);
                            $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($prompt);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $prompt = aiomatic_substr($prompt, 0, $string_len);
                                $prompt = trim($prompt);
                                $query_token_count = count(aiomatic_encode($prompt));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $thread_id = '';
                            $aierror = '';
                            $finish_reason = '';
                            remove_filter('aiomatic_ai_reply_raw', 'aiomatic_agent_handle_god_mode_response');
                            $generated_text = aiomatic_generate_text($token, $model, $prompt, $available_tokens, 1, 1, 0, 0, false, 'aiThinking', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', '', $thread_id, '', 'disabled', '', false, false, array(), '', '', '');
                            add_filter('aiomatic_ai_reply_raw', 'aiomatic_agent_handle_god_mode_response', 10, 2);
                            if($generated_text === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => '[ERROR] Failed to generate content using AI writer: ' . $model . ' - error: ' . $aierror,
                                    'assistant_message' => $as_mes
                                ));
                            }
                            else
                            {
                                $new_post_content = aiomatic_sanitize_ai_result($generated_text);
                                if(empty($new_post_content))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => '[ERROR] No content returned by the AI writer!',
                                        'assistant_message' => $as_mes
                                    ));
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => $new_post_content,
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            }
                            continue;
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'youtube_video_captions') 
                    {
                        if(isset($tool_call->function->arguments->url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $zurl = $tool_call->function->arguments->url;
                            if (empty($zurl)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $returned_caption = '';
                            $video_id = '';
                            preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $zurl, $amatches);
                            if(isset($amatches[1]))
                            {
                                $video_id = $amatches[1];
                            }
                            $caprez = false;
                            if(!empty($video_id))
                            {
                                try
                                {
                                    $caprez = aiomatic_get_video_transcript($video_id);
                                }
                                catch(Exception $e)
                                {
                                    try 
                                    {
                                        $caprez = aiomatic_get_video_transcript_2($video_id);
                                    } 
                                    catch (Exception $e) 
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to get transcript for video ID ' . $video_id . ': ' . $e->getMessage());
                                        }
                                    }
                                }
                            }
                            if(is_array($caprez) && isset($caprez['text']))
                            {
                                $returned_caption = $caprez['text'];
                            }
                            if(empty($returned_caption))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse YouTube Video captions from URL (no data returned): ' . $zurl,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $returned_caption = aiomatic_substr($returned_caption, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $returned_caption,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'youtube_video_search') 
                    {
                        if(isset($tool_call->function->arguments->keyword))
                        {
                            $result = '';
                            $keyword = $tool_call->function->arguments->keyword;
                            if (empty($keyword)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty keyword parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $new_vid = aiomatic_get_video($keyword, '', array());
                            if(empty($new_vid))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse YouTube video search results for keyword (no data returned): ' . $keyword,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                aiomatic_agent_add_tool_direct_message($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $new_vid,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'keyword parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'wp_send_email') 
                    {
                        if(isset($tool_call->function->arguments->subject) && isset($tool_call->function->arguments->content) && isset($tool_call->function->arguments->recipient_email))
                        {
                            $result = '';
                            $subject = $tool_call->function->arguments->subject;
                            $content = $tool_call->function->arguments->content;
                            $recipient_email = $tool_call->function->arguments->recipient_email;
                            if (empty($subject) || empty($content) || empty($recipient_email)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty subject, content or recipient_email parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                $admin_mail = get_bloginfo('admin_email');
                                $headers[] = 'From: Aimogen Plugin Chatbot <' . $admin_mail . '>';
                                $headers[] = 'Reply-To: ' . $admin_mail;
                                $headers[] = 'X-Mailer: PHP/' . phpversion();
                                $headers[] = 'Content-Type: text/html';
                                $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                $sent = wp_mail($recipient_email, $subject, $content, $headers);
                                if($sent === false)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to send email to address: ' . $recipient_email,
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'OK',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'subject, content or recipient_email parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'call_webhook') 
                    {
                        if(isset($tool_call->function->arguments->webhook_url) && isset($tool_call->function->arguments->method_selector))
                        {
                            $webhook_url = $tool_call->function->arguments->webhook_url;
                            if (empty($webhook_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty webhook_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $webhook_method = $tool_call->function->arguments->method_selector;
                            if (empty($webhook_method)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty method_selector parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content_type = '';
                            if(isset($tool_call->function->arguments->content_type))
                            {
                                $content_type = $tool_call->function->arguments->content_type;
                            }
                            $post_template = '';
                            if(isset($tool_call->function->arguments->data))
                            {
                                $post_template = $tool_call->function->arguments->data;
                            }
                            $headers_template = '';
                            if(isset($tool_call->function->arguments->headers))
                            {
                                $headers_template = $tool_call->function->arguments->headers;
                            }
                            $urlParsed = wp_parse_url( $webhook_url, PHP_URL_HOST );
                            if ( filter_var( $webhook_url, FILTER_VALIDATE_URL ) === FALSE || empty( $urlParsed ) )
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid webhook_url entered ' . $webhook_url,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else if ( $content_type == 'JSON' && empty( json_decode( $post_template, TRUE ) ) )
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'The JSON data must be valid ' . $webhook_url,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $headers = [];
                            if(!empty($headers_template))
                            {
                                $headers_template_arr = preg_split('/\r\n|\r|\n/', trim($headers_template));
                                foreach($headers_template_arr as $arr_fr)
                                {
                                    if(!empty(trim($arr_fr)) && strstr($arr_fr, '=>'))
                                    {
                                        $small_arr = explode('=>', $arr_fr);
                                        $headers[] = trim($small_arr[0]) . ':' . trim($small_arr[1]);
                                    }
                                }
                            }
                            $content_params = [];
                            if(!empty($post_template))
                            {
                                $post_template_arr = preg_split('/\r\n|\r|\n/', trim($post_template));
                                foreach($post_template_arr as $arr_fr)
                                {
                                    if(!empty(trim($arr_fr)) && strstr($arr_fr, '=>'))
                                    {
                                        $small_arr = explode('=>', $arr_fr);
                                        $content_params[trim($small_arr[0])] = trim($small_arr[1]);
                                    }
                                }
                            }
                            $ch = curl_init();
                            if ($ch === false) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to init curl in webhook execution',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                                $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                $randomness = array_rand($prx);
                                curl_setopt( $ch, CURLOPT_PROXY, trim($prx[$randomness]));
                                if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                {
                                    $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                    if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                    {
                                        curl_setopt( $ch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                    }
                                }
                            }
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            if ($webhook_method == 'POST' || $webhook_method == 'PUT' || $webhook_method == 'DELETE') 
                            {
                                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook_method);
                                if (!empty($content_params) && $content_type == 'form_data') {
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content_params));
                                } elseif (!empty($post_template) && $content_type == 'JSON') {
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_template));
                                    $headers[] = 'Content-Type: application/json';
                                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                                }
                            }
                            else
                            {
                                $query_string = http_build_query($content_params);
                                $webhook_url = $webhook_url . (strpos($webhook_url, '?') === false ? '?' : '&') . $query_string;
                            }
                            curl_setopt($ch, CURLOPT_URL, $webhook_url);

                            $response = curl_exec($ch);
                            if($response === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to send webhook request to ' . $webhook_url,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $err = curl_error($ch);
                            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);
                            if ($err) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Webhook request error to URL ' . $webhook_url . ' - error: ' . $err,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if ($statusCode >= 200 && $statusCode <= 299) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Webhook URL called successfully!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            } 
                            else 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Webhook unexpected return code to URL ' . $webhook_url . ' - return code: ' . $statusCode,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'webhook_url or method_selector parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_facebook_post') 
                    {
                        if(isset($tool_call->function->arguments->content))
                        {
                            $result = '';
                            $zcontent = $tool_call->function->arguments->content;
                            if (empty($zcontent)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $fbomatic_active = false;
                                if (is_plugin_active('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php')) 
                                {
                                    $fbomatic_active = true;
                                }
                                if(!$fbomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (F-omatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $furl = '';
                                if(isset($tool_call->function->arguments->url))
                                {
                                    $furl = $tool_call->function->arguments->url;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['facebook_post_select']) && $aiomatic_Chatbot_Settings['facebook_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['facebook_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No page where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php' => array('F-omatic Automatic Post Generator', 'https://1.envato.market/fbomatic')));
                                $return_me = aiomatic_post_to_facebook($card_type_found, $zcontent, $furl, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Facebook posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Facebook posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Facebook posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Facebook posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Facebook posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_facebook_image') 
                    {
                        if(isset($tool_call->function->arguments->image_url))
                        {
                            $result = '';
                            $image_url = $tool_call->function->arguments->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $fbomatic_active = false;
                                if (is_plugin_active('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php')) 
                                {
                                    $fbomatic_active = true;
                                }
                                if(!$fbomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (F-omatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $caption = '';
                                if(isset($tool_call->function->arguments->caption))
                                {
                                    $caption = $tool_call->function->arguments->caption;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['facebook_post_select']) && $aiomatic_Chatbot_Settings['facebook_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['facebook_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No page where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php' => array('F-omatic Automatic Post Generator', 'https://1.envato.market/fbomatic')));
                                $return_me = aiomatic_post_image_to_facebook($card_type_found, $caption, $image_url, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Facebook image posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook image posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Facebook image posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Facebook image posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook image posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Facebook image posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Facebook image posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_twitter_x_post') 
                    {
                        if(isset($tool_call->function->arguments->content))
                        {
                            $result = '';
                            $zcontent = $tool_call->function->arguments->content;
                            if (empty($zcontent)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $twitomatic_active = false;
                                if (is_plugin_active('twitomatic-twitter-post-generator/twitomatic-twitter-post-generator.php')) 
                                {
                                    $twitomatic_active = true;
                                }
                                if(!$twitomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Twitomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $image_url = '';
                                if(isset($tool_call->function->arguments->image_url))
                                {
                                    $image_url = $tool_call->function->arguments->image_url;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('twitomatic-twitter-post-generator/twitomatic-twitter-post-generator.php' => array('Twitomatic Automatic Post Generator', 'https://1.envato.market/twitomatic')));
                                $return_me = aiomatic_post_to_twitter($card_type_found, $zcontent, $image_url);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Twitter posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Twitter posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Twitter posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Twitter posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Twitter posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Twitter posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Twitter posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_threads_post') 
                    {
                        if(isset($tool_call->function->arguments->content))
                        {
                            $result = '';
                            $zcontent = $tool_call->function->arguments->content;
                            if (empty($zcontent)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $threadsomatic_active = false;
                                if (is_plugin_active('threadsomatic-threads-auto-poster/threadsomatic-threads-auto-poster.php')) 
                                {
                                    $threadsomatic_active = true;
                                }
                                if(!$threadsomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Threadsomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $image_url = '';
                                if(isset($tool_call->function->arguments->image_url))
                                {
                                    $image_url = $tool_call->function->arguments->image_url;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('threadsomatic-threads-auto-poster/threadsomatic-threads-auto-poster.php' => array('Threadsomatic Threads Auto Poster', 'https://wpbay.com/product/threadsomatic-threads-auto-poster/')));
                                $return_me = aiomatic_post_to_threads($card_type_found, $zcontent, $image_url);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Threads posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Threads posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Threads posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Threads posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Threads posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Threads posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Threads posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_instagram_post') 
                    {
                        if(isset($tool_call->function->arguments->image_url))
                        {
                            $result = '';
                            $image_url = $tool_call->function->arguments->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('instamatic-instagram-post-generator/instamatic-instagram-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Instamatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $content = '';
                                if(isset($tool_call->function->arguments->content))
                                {
                                    $content = $tool_call->function->arguments->content;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('instamatic-instagram-post-generator/instamatic-instagram-post-generator.php' => array('iMediamatic Automatic Post Generator', 'https://1.envato.market/instamatic')));
                                $return_me = aiomatic_post_image_to_instagram($card_type_found, $content, $image_url);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Instagram posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Instagram posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Instagram posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Instagram posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Instagram posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Instagram posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Instagram posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_pinterest_post') 
                    {
                        if(isset($tool_call->function->arguments->image_url))
                        {
                            $result = '';
                            $image_url = $tool_call->function->arguments->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('pinterestomatic-pinterest-post-generator/pinterestomatic-pinterest-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Pinterestomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['pinterest_post_select']) && $aiomatic_Chatbot_Settings['pinterest_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['pinterest_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No boards where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $title = '';
                                if(isset($tool_call->function->arguments->title))
                                {
                                    $title = $tool_call->function->arguments->title;
                                }
                                $description = '';
                                if(isset($tool_call->function->arguments->description))
                                {
                                    $description = $tool_call->function->arguments->description;
                                }
                                $pin_url = '';
                                if(isset($tool_call->function->arguments->pin_url))
                                {
                                    $pin_url = $tool_call->function->arguments->pin_url;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('pinterestomatic-pinterest-post-generator/pinterestomatic-pinterest-post-generator.php' => array('Pinterestomatic Automatic Post Generator', 'https://1.envato.market/pinterestomatic')));
                                $return_me = aiomatic_post_image_to_pinterest($card_type_found, $description, $title, $pin_url, $image_url, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Pinterest posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Pinterest posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Pinterest posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Pinterest posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Pinterest posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Pinterest posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Pinterest posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_google_my_business_post') 
                    {
                        if(isset($tool_call->function->arguments->content) && isset($tool_call->function->arguments->image_url))
                        {
                            $result = '';
                            $image_url = $tool_call->function->arguments->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content = $tool_call->function->arguments->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('businessomatic-google-my-business-post-generator/businessomatic-google-my-business-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Businessomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['business_post_select']) && $aiomatic_Chatbot_Settings['business_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['business_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No pages where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('businessomatic-google-my-business-post-generator/businessomatic-google-my-business-post-generator.php' => array('Businessomatic Automatic Post Generator', 'https://1.envato.market/businessomatic')));
                                $return_me = aiomatic_post_to_gmb($card_type_found, $content, $image_url, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('GMB posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'GMB posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse GMB posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse GMB posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'GMB posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('GMB posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'GMB posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url or content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_youtube_community_post') 
                    {
                        if(isset($tool_call->function->arguments->content) && isset($tool_call->function->arguments->post_type))
                        {
                            $result = '';
                            $post_type = $tool_call->function->arguments->post_type;
                            if (empty($post_type)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty post_type parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $post_type = trim($post_type);
                            if($post_type != 'image' && $post_type != 'text')
                            {
                                $post_type = 'text';
                            }
                            $content = $tool_call->function->arguments->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $image_url = '';
                            if(isset($tool_call->function->arguments->image_url))
                            {
                                $image_url = $tool_call->function->arguments->image_url;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('youtubomatic-youtube-post-generator/youtubomatic-youtube-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Youtubomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                if($image_url != '')
                                {
                                    $media = array($image_url);
                                }
                                else
                                {
                                    $media = array();
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('youtubomatic-youtube-post-generator/youtubomatic-youtube-post-generator.php' => array('Youtubomatic Automatic Post Generator', 'https://1.envato.market/youtubomatic')));
                                $return_me = aiomatic_post_to_youtube_community($card_type_found, $content, $post_type, $media);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('YouTube Community posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'YouTube Community posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse YouTube Community posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse YouTube Community posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'YouTube Community posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('YouTube Community posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'YouTube Community posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content or post_type parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_reddit_post') 
                    {
                        if(isset($tool_call->function->arguments->content) && isset($tool_call->function->arguments->title))
                        {
                            $result = '';
                            $title = $tool_call->function->arguments->title;
                            if (empty($title)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty title parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content = $tool_call->function->arguments->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('redditomatic-reddit-post-generator/redditomatic-reddit-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Redditomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $subreddit_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['subreddits_list']) && $aiomatic_Chatbot_Settings['subreddits_list'] != '') {
                                    $subreddit_to_post = $aiomatic_Chatbot_Settings['subreddits_list'];
                                }
                                if (empty($subreddit_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No subreddits were defined where to publish the post',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('redditomatic-reddit-post-generator/redditomatic-reddit-post-generator.php' => array('Redditomatic Automatic Post Generator', 'https://1.envato.market/redditomatic')));
                                $return_me = aiomatic_post_to_reddit($card_type_found, $title, $content, 'auto', $subreddit_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Reddit posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Reddit posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Reddit posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Reddit posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Reddit posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Reddit posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Reddit posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content or title parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->function->name === 'publish_linkedin_post') 
                    {
                        if(isset($tool_call->function->arguments->content) && isset($tool_call->function->arguments->title))
                        {
                            $result = '';
                            $title = $tool_call->function->arguments->title;
                            if (empty($title)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty title parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content = $tool_call->function->arguments->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $description = '';
                            $post_link = '';
                            $image_url = '';
                            if(isset($tool_call->function->arguments->description))
                            {
                                $description = $tool_call->function->arguments->description;
                            }
                            if(isset($tool_call->function->arguments->link))
                            {
                                $post_link = $tool_call->function->arguments->link;
                            }
                            if(isset($tool_call->function->arguments->image_url))
                            {
                                $image_url = $tool_call->function->arguments->image_url;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('linkedinomatic-linkedin-post-generator/linkedinomatic-linkedin-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Linkedinomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $selected_pages = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['linkedin_selected_pages']) && $aiomatic_Chatbot_Settings['linkedin_selected_pages'] != '') {
                                    $selected_pages = $aiomatic_Chatbot_Settings['linkedin_selected_pages'];
                                }
                                if (empty($selected_pages)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No pages selected where to post to LinkedIn',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('linkedinomatic-linkedin-post-generator/linkedinomatic-linkedin-post-generator.php' => array('Linkedinomatic Automatic Post Generator', 'https://1.envato.market/linkedinomatic')));
                                $return_me = aiomatic_post_to_linkedin($card_type_found, $content, $image_url, $title, $post_link, $description, '1', $selected_pages);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('LinkedIn posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'LinkedIn posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse LinkedIn posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse LinkedIn posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'LinkedIn posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('LinkedIn posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'LinkedIn posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content or title parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                }
            }
        }
    }
    return $reply;
    };
    $agent_responses_god_mode_callback = function($reply, $query = array()) use ($agent) {
    if(!isset($reply->output) || !is_array($reply->output))
    {
        return $reply;
    }
    $function_found = false;
    foreach($reply->output as $aiout)
    {
        if($aiout->type && $aiout->type == 'function_call')
        {
            $function_found = true;
        }
    }
    if ($function_found == true) 
    {
        $ctx = apply_filters('aiomatic_agent_context', []);
        $current_agent = null;
        $current_step = 0;

        if (!empty($ctx['agent_id'])) {
            $current_agent = Aiomatic_Agent::get_instance_by_id((int)$ctx['agent_id']);
        }
        if (!$current_agent || !$current_agent->is_api_level_tool_execution_allowed()) {
            return $reply;
        }
        if (!empty($ctx['step'])) {
            $current_step = (int)$ctx['step'];
        }
        {
            $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
            require_once(__DIR__ . '/res/amazon-direct.php');
            foreach($reply->output as $tool_call)
            {
                if (isset($tool_call->type) && $tool_call->type == 'function_call')
                {
                    $result = false;
                    if (isset($tool_call->arguments) && is_string($tool_call->arguments)) 
                    {
                        $targs = json_decode($tool_call->arguments);
                        if($targs !== null)
                        {
                            $tool_call->arguments = $targs;
                        }
                        else
                        {
                            $strips = stripslashes($tool_call->arguments);
                            $targs = json_decode($strips);
                            if($targs !== null)
                            {
                                $tool_call->arguments = $targs;
                            }
                            else
                            {
                                $jsons = aiomatic_parse_multiple_json($tool_call->arguments);
                                if(!empty($jsons) && isset($jsons[0]))
                                {
                                    $tool_call->arguments = $jsons[0];
                                }
                            }
                        }
                    }
                    if(!isset($tool_call->arguments) || !isset($tool_call->name))
                    {
                        continue;
                    }
                    if ($current_agent) {
                        $args = $tool_call->arguments;

                        if (is_object($args)) {
                            $args = json_decode(wp_json_encode($args), true);
                        }
                        if (!is_array($args)) {
                            $args = [];
                        }

                        $current_agent->log_native_tool_call(
                            $current_step,
                            $tool_call->name,
                            $args
                        );
                        if($current_agent->is_debug_mode())
                        {
                            $current_agent->debug_log('CALLING TOOL [' . $tool_call->name . ']: ' . print_r($args, true));
                        }
                    }
                    $as_mes = '';
                    if (!aiomatic_is_restricted_function_allowed($tool_call->name)) {
                        if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                        {
                            aiomatic_log_to_file('Blocked tool (central filter): ' . $tool_call->name);
                        }
                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => 'You are not allowed to call this function (you need to be admin)',
                            'assistant_message' => $as_mes
                        ));
                        continue;
                    }
                    $fun_args = $tool_call->arguments;
                    if ($tool_call->name === 'generate_chart') 
                    {
                        if(isset($fun_args->shortcode))
                        {
                            $shortcode = $fun_args->shortcode;
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => do_shortcode($shortcode),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'shortcode parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_openai') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (!isset($aiomatic_Main_Settings['app_id'])) 
                            {
                                $aiomatic_Main_Settings['app_id'] = '';
                            }
                            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
                            $appids = array_filter($appids);
                            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
                            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
                            if (empty($token))
                            {
                                aiomatic_log_to_file('You need to enter an OpenAI API key for this to work!');
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size']) && trim($aiomatic_Chatbot_Settings['ai_image_size']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_model']) && trim($aiomatic_Chatbot_Settings['ai_image_model']) != '')
                            {
                                $model = trim($aiomatic_Chatbot_Settings['ai_image_model']);
                            }
                            else
                            {
                                $model = 'gpt-image-2';
                            }
                            if(empty($result))
                            {
                                $aierror = '';
                                $airesult = aiomatic_generate_ai_image($token, 1, $prompt, $image_size, 'chatFunctionDalleImage', false, 0, $aierror, $model, $prompt);
                                if($airesult !== false && is_array($airesult))
                                {
                                    foreach($airesult as $tmpimg)
                                    {
                                        $tmpimg = aiomatic_sanitize_image_src($tmpimg);
                                        if($tmpimg !== false)
                                        {
                                            $result = '<img class="image_max_w_ai" src="' . $tmpimg . '">';
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Dall-E image in AI chatbot: ' . $aierror);
                                    if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                    {
                                        $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                    }
                                    else
                                    {
                                        $result = 'Image creation failed, please try again later.';
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => $result,
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_stable_diffusion') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_stable']) && trim($aiomatic_Chatbot_Settings['ai_image_size_stable']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_stable']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            if (isset($aiomatic_Chatbot_Settings['stable_model']) && trim($aiomatic_Chatbot_Settings['stable_model']) != '')
                            {
                                $model = trim($aiomatic_Chatbot_Settings['stable_model']);
                            }
                            else
                            {
                                $model = AIMOGEN_STABLE_DEFAULT_MODE;
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_stability_image($prompt, $height, $width, 'chatFunctionStableImage', 0, false, $aierror, false, $model, '', 0);
                            if($airesult !== false && isset($airesult[1]))
                            {
                                $airesult[1] = aiomatic_sanitize_image_src($airesult[1]);
                                if($airesult[1] !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult[1] . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Stable image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_google') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                            {
                                $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                            }
                            else
                            {
                                $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_image_google($prompt, $model, 'chatFunctionGoogleImage', false, $aierror, false);
                            if($airesult !== false && isset($airesult[1]))
                            {
                                $airesult[1] = aiomatic_sanitize_image_src($airesult[1]);
                                if($airesult[1] !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult[1] . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Google image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_midjourney') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_midjourney']) && trim($aiomatic_Chatbot_Settings['ai_image_size_midjourney']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_midjourney']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_ai_image_midjourney($prompt, $width, $height, 'chatFunctionMidjourneyImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Midjourney image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_replicate') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_replicate']) && trim($aiomatic_Chatbot_Settings['ai_image_size_replicate']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_replicate']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_replicate_image($prompt, $width, $height, 'chatFunctionReplicateImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Replicate image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_ideogram') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_image_size_ideogram']) && trim($aiomatic_Chatbot_Settings['ai_image_size_ideogram']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_image_size_ideogram']);
                            }
                            else
                            {
                                $image_size = '512x512';
                            }
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_ideogram_image($prompt, $width, $height, 'chatFunctionIdeogramImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Ideogram image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_image_cloudflare') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $prompt = $fun_args->prompt;
                            if (empty($prompt))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $image_size = '512x512';
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            $aierror = '';
                            $airesult = aiomatic_generate_cloudflare_image($prompt, $width, $height, 'chatFunctionCloudflareImage', false, $aierror);
                            if($airesult !== false)
                            {
                                $airesult = aiomatic_sanitize_image_src($airesult);
                                if($airesult !== false)
                                {
                                    $result = '<img class="image_max_w_ai" src="' . $airesult . '">';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Cloudflare image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']) != '')
                                {
                                    $result = trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']);
                                }
                                else
                                {
                                    $result = 'Image creation failed, please try again later.';
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            aiomatic_agent_add_tool_direct_message($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $result,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'create_stable_diffusion_video') 
                    {
                        if(isset($fun_args->image_url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $image_url = $fun_args->image_url;
                            if (empty($image_url))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url sent',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['ai_video_size_stable']) && trim($aiomatic_Chatbot_Settings['ai_video_size_stable']) != '')
                            {
                                $image_size = trim($aiomatic_Chatbot_Settings['ai_video_size_stable']);
                            }
                            else
                            {
                                $image_size = '768x768';
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_stability_video($image_url, $image_size, 'chatbotStableVideo', 0, false, $aierror, false);
                            if($response_text !== false && isset($response_text[1]))
                            {
                                $result = '<div style="padding-bottom:56.25%; position:relative; display:block; width: 100%"><iframe src="' . $response_text[1] . '" width="100%" height="100%" style="position:absolute; top:0; left: 0" allowfullscreen webkitallowfullscreen frameborder="0"></iframe></div>';
                                aiomatic_agent_add_tool_direct_message($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Dall-E video in AI chatbot: ' . $aierror);
                                $result = 'Video creation failed, please try again later.';
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'search_clickbank') 
                    {
                        if(isset($fun_args->query))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $asin = $fun_args->query;
                            if (empty($asin)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty search query provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['clickbank_affiliate_id']) && trim($aiomatic_Chatbot_Settings['clickbank_affiliate_id']) != '')
                            {
                                $cb_affiliate_id = trim($aiomatic_Chatbot_Settings['clickbank_affiliate_id']);
                            }
                            else
                            {
                                $cb_affiliate_id = '';
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_products_cb']) && trim($aiomatic_Chatbot_Settings['max_products_cb']) != '')
                            {
                                $max_product_count = trim($aiomatic_Chatbot_Settings['max_products_cb']);
                            }
                            else
                            {
                                $max_product_count = '3-4';
                            }
                            if (isset($aiomatic_Chatbot_Settings['listing_template_cb']) && trim($aiomatic_Chatbot_Settings['listing_template_cb']) != '')
                            {
                                $listing_template = trim($aiomatic_Chatbot_Settings['listing_template_cb']);
                            }
                            else
                            {
                                $listing_template = '%%product_counter%%. %%product_title%% - Desciption: %%product_description%% - Link: %%product_url%% - Price: %%product_price%%';
                            }
                            
                            if(strstr($max_product_count, '-') !== false)
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                if(is_numeric($minx) && is_numeric($maxx))
                                {
                                    $max_product_count = rand(intval($minx), intval($maxx));
                                }
                                else
                                {
                                    if(is_numeric($minx))
                                    {
                                        $max_product_count = intval($minx);
                                    }
                                    elseif(is_numeric($maxx))
                                    {
                                        $max_product_count = intval($maxx);
                                    }
                                    else
                                    {
                                        $max_product_count = 100;
                                    }
                                }
                            }
                            if(!empty($max_product_count) && is_numeric($max_product_count))
                            {
                                $max_prod = intval($max_product_count);
                            }
                            else
                            {
                                $max_prod = 100;
                            }
                            $neg_keywords = '';
                            $item_category = 'All';
                            $shipable_only = '';
                            $pitch_plus = '';
                            $one_time = '';
                            $recurring = '';
                            $affiliate_tools = '';
                            $spotlight = '';
                            $mobile_hoplink = '';
                            $item_language = '';
                            $activation = '';
                            $item_gravity = '';
                            $dollar_sale = '';
                            $dollar_sale_av = '';
                            $rebill_total = '';
                            $per_sale = '';
                            $per_rebill = '';
                            $sort_results_cb = '';
                            $amazresult = aiomatic_clickbank_get_post($cb_affiliate_id, $asin, $neg_keywords, $item_category, $shipable_only, $pitch_plus, $one_time, $recurring, $affiliate_tools, $spotlight, $mobile_hoplink, $item_language, $activation, $item_gravity, $dollar_sale, $dollar_sale_av, $rebill_total, $per_sale, $per_rebill, $sort_results_cb, $max_prod);
                            if(is_array($amazresult) && ((isset($amazresult['status']) && $amazresult['status'] == 'nothing') || count($amazresult) == 0))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No ClickBank products found for query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'An error occurred while search ClickBank for: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            
                            $final_result = '';
                            $counter = 1;
                            foreach($amazresult as $myprod)
                            {
                                $copy_template = $listing_template;
                                $copy_template = str_replace('%%product_counter%%', $counter, $copy_template);
                                $copy_template = str_replace('%%product_title%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_title)), $copy_template);
                                $copy_template = str_replace('%%product_description%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_desc)), $copy_template);
                                $copy_template = str_replace('%%product_url%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_url)), $copy_template);
                                $copy_template = str_replace('%%product_price%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_price)), $copy_template);
                                $copy_template = str_replace('%%product_list_price%%', trim(preg_replace('/\s+/', ' ', $myprod->product_list_price)), $copy_template);
                                $copy_template = str_replace('%%product_image%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_img)), $copy_template);
                                $copy_template = str_replace('%%product_cart_url%%', trim(preg_replace('/\s+/', ' ', $myprod->cart_url)), $copy_template);
                                $copy_template = str_replace('%%product_images_urls%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs)), $copy_template);
                                $copy_template = str_replace('%%product_images%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs_html)), $copy_template);
                                $copy_template = str_replace('%%product_reviews%%', trim(preg_replace('/\s+/', ' ', implode(PHP_EOL, $myprod->item_reviews))), $copy_template);
                                //new
                                $copy_template = str_replace('%%product_score%%', trim(preg_replace('/\s+/', ' ', $myprod->item_score)), $copy_template);
                                $copy_template = str_replace('%%product_language%%', trim(preg_replace('/\s+/', ' ', $myprod->language)), $copy_template);
                                $copy_template = str_replace('%%product_edition%%', trim(preg_replace('/\s+/', ' ', $myprod->edition)), $copy_template);
                                $copy_template = str_replace('%%product_pages_count%%', trim(preg_replace('/\s+/', ' ', $myprod->pages_count)), $copy_template);
                                $copy_template = str_replace('%%product_publication_date%%', trim(preg_replace('/\s+/', ' ', $myprod->publication_date)), $copy_template);
                                $copy_template = str_replace('%%product_contributors%%', trim(preg_replace('/\s+/', ' ', $myprod->contributors)), $copy_template);
                                $copy_template = str_replace('%%product_manufacturer%%', trim(preg_replace('/\s+/', ' ', $myprod->manufacturer)), $copy_template);
                                $copy_template = str_replace('%%product_binding%%', trim(preg_replace('/\s+/', ' ', $myprod->binding)), $copy_template);
                                $copy_template = str_replace('%%product_product_group%%', trim(preg_replace('/\s+/', ' ', $myprod->product_group)), $copy_template);
                                $copy_template = str_replace('%%product_rating%%', trim(preg_replace('/\s+/', ' ', $myprod->rating)), $copy_template);
                                $copy_template = str_replace('%%product_ean%%', trim(preg_replace('/\s+/', ' ', $myprod->eans)), $copy_template);
                                $copy_template = str_replace('%%product_part_no%%', trim(preg_replace('/\s+/', ' ', $myprod->part_no)), $copy_template);
                                $copy_template = str_replace('%%product_model%%', trim(preg_replace('/\s+/', ' ', $myprod->model)), $copy_template);
                                $copy_template = str_replace('%%product_warranty%%', trim(preg_replace('/\s+/', ' ', $myprod->warranty)), $copy_template);
                                $copy_template = str_replace('%%product_color%%', trim(preg_replace('/\s+/', ' ', $myprod->color)), $copy_template);
                                $copy_template = str_replace('%%product_is_adult%%', trim(preg_replace('/\s+/', ' ', $myprod->is_adult)), $copy_template);
                                $copy_template = str_replace('%%product_dimensions%%', trim(preg_replace('/\s+/', ' ', $myprod->dimensions)), $copy_template);
                                $copy_template = str_replace('%%product_size%%', trim(preg_replace('/\s+/', ' ', $myprod->size)), $copy_template);
                                $copy_template = str_replace('%%product_unit_count%%', trim(preg_replace('/\s+/', ' ', $myprod->unit_count)), $copy_template);
                                
                                $counter++;
                                $final_result .= $copy_template . '\r\n'; 
                            }
                            $final_result = trim($final_result);
                            $final_result = aiomatic_substr($final_result, 0, 400000);
                            if(!empty($final_result))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                            else
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'ClickBank did not return info for this query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'search_amazon') 
                    {
                        if(isset($fun_args->query))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $asin = $fun_args->query;
                            if (empty($asin)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty search query provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['affiliate_id']) && trim($aiomatic_Chatbot_Settings['affiliate_id']) != '')
                            {
                                $aff_id = trim($aiomatic_Chatbot_Settings['affiliate_id']);
                            }
                            else
                            {
                                $aff_id = '';
                            }
                            if (isset($aiomatic_Chatbot_Settings['target_country']) && trim($aiomatic_Chatbot_Settings['target_country']) != '')
                            {
                                $target_country = trim($aiomatic_Chatbot_Settings['target_country']);
                            }
                            else
                            {
                                $target_country = 'com';
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_products']) && trim($aiomatic_Chatbot_Settings['max_products']) != '')
                            {
                                $max_product_count = trim($aiomatic_Chatbot_Settings['max_products']);
                            }
                            else
                            {
                                $max_product_count = '3-4';
                            }
                            if (isset($aiomatic_Chatbot_Settings['sort_results']) && trim($aiomatic_Chatbot_Settings['sort_results']) != '')
                            {
                                $amaz_sort_results = trim($aiomatic_Chatbot_Settings['sort_results']);
                            }
                            else
                            {
                                $amaz_sort_results = 'none';
                            }
                            if (isset($aiomatic_Chatbot_Settings['listing_template']) && trim($aiomatic_Chatbot_Settings['listing_template']) != '')
                            {
                                $listing_template = trim($aiomatic_Chatbot_Settings['listing_template']);
                            }
                            else
                            {
                                $listing_template = '%%product_counter%%. %%product_title%% - Desciption: %%product_description%% - Link: %%product_url%% - Price: %%product_price%%';
                            }
                            
                            if(strstr($max_product_count, '-') !== false)
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                if(is_numeric($minx) && is_numeric($maxx))
                                {
                                    $max_product_count = rand(intval($minx), intval($maxx));
                                }
                                else
                                {
                                    if(is_numeric($minx))
                                    {
                                        $max_product_count = intval($minx);
                                    }
                                    elseif(is_numeric($maxx))
                                    {
                                        $max_product_count = intval($maxx);
                                    }
                                    else
                                    {
                                        $max_product_count = 100;
                                    }
                                }
                            }
                            if(!empty($max_product_count) && is_numeric($max_product_count))
                            {
                                $max_prod = intval($max_product_count);
                            }
                            else
                            {
                                $max_prod = 100;
                            }
                            $amazresult = aiomatic_amazon_get_post($asin, trim($aff_id), $target_country, '', '', $amaz_sort_results, $max_prod, '1', array());
                            if(is_array($amazresult) && ((isset($amazresult['status']) && $amazresult['status'] == 'nothing') || count($amazresult) == 0))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No Amazon products found for query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'An error occurred while search Amazon for: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            
                            $final_result = '';
                            $counter = 1;
                            foreach($amazresult as $myprod)
                            {
                                $copy_template = $listing_template;
                                $copy_template = str_replace('%%product_counter%%', $counter, $copy_template);
                                $copy_template = str_replace('%%product_title%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_title)), $copy_template);
                                $copy_template = str_replace('%%product_description%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_desc)), $copy_template);
                                $copy_template = str_replace('%%product_url%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_url)), $copy_template);
                                $copy_template = str_replace('%%product_price%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_price)), $copy_template);
                                $copy_template = str_replace('%%product_list_price%%', trim(preg_replace('/\s+/', ' ', $myprod->product_list_price)), $copy_template);
                                $copy_template = str_replace('%%product_image%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_img)), $copy_template);
                                $copy_template = str_replace('%%product_cart_url%%', trim(preg_replace('/\s+/', ' ', $myprod->cart_url)), $copy_template);
                                $copy_template = str_replace('%%product_images_urls%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs)), $copy_template);
                                $copy_template = str_replace('%%product_images%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs_html)), $copy_template);
                                $copy_template = str_replace('%%product_reviews%%', trim(preg_replace('/\s+/', ' ', implode(PHP_EOL, $myprod->item_reviews))), $copy_template);
                                //new
                                $copy_template = str_replace('%%product_score%%', trim(preg_replace('/\s+/', ' ', $myprod->item_score)), $copy_template);
                                $copy_template = str_replace('%%product_language%%', trim(preg_replace('/\s+/', ' ', $myprod->language)), $copy_template);
                                $copy_template = str_replace('%%product_edition%%', trim(preg_replace('/\s+/', ' ', $myprod->edition)), $copy_template);
                                $copy_template = str_replace('%%product_pages_count%%', trim(preg_replace('/\s+/', ' ', $myprod->pages_count)), $copy_template);
                                $copy_template = str_replace('%%product_publication_date%%', trim(preg_replace('/\s+/', ' ', $myprod->publication_date)), $copy_template);
                                $copy_template = str_replace('%%product_contributors%%', trim(preg_replace('/\s+/', ' ', $myprod->contributors)), $copy_template);
                                $copy_template = str_replace('%%product_manufacturer%%', trim(preg_replace('/\s+/', ' ', $myprod->manufacturer)), $copy_template);
                                $copy_template = str_replace('%%product_binding%%', trim(preg_replace('/\s+/', ' ', $myprod->binding)), $copy_template);
                                $copy_template = str_replace('%%product_product_group%%', trim(preg_replace('/\s+/', ' ', $myprod->product_group)), $copy_template);
                                $copy_template = str_replace('%%product_rating%%', trim(preg_replace('/\s+/', ' ', $myprod->rating)), $copy_template);
                                $copy_template = str_replace('%%product_ean%%', trim(preg_replace('/\s+/', ' ', $myprod->eans)), $copy_template);
                                $copy_template = str_replace('%%product_part_no%%', trim(preg_replace('/\s+/', ' ', $myprod->part_no)), $copy_template);
                                $copy_template = str_replace('%%product_model%%', trim(preg_replace('/\s+/', ' ', $myprod->model)), $copy_template);
                                $copy_template = str_replace('%%product_warranty%%', trim(preg_replace('/\s+/', ' ', $myprod->warranty)), $copy_template);
                                $copy_template = str_replace('%%product_color%%', trim(preg_replace('/\s+/', ' ', $myprod->color)), $copy_template);
                                $copy_template = str_replace('%%product_is_adult%%', trim(preg_replace('/\s+/', ' ', $myprod->is_adult)), $copy_template);
                                $copy_template = str_replace('%%product_dimensions%%', trim(preg_replace('/\s+/', ' ', $myprod->dimensions)), $copy_template);
                                $copy_template = str_replace('%%product_size%%', trim(preg_replace('/\s+/', ' ', $myprod->size)), $copy_template);
                                $copy_template = str_replace('%%product_unit_count%%', trim(preg_replace('/\s+/', ' ', $myprod->unit_count)), $copy_template);
                                
                                $counter++;
                                $final_result .= $copy_template . '\r\n'; 
                            }
                            $final_result = trim($final_result);
                            $final_result = aiomatic_substr($final_result, 0, 400000);
                            if(!empty($final_result))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                            else
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Amazon did not return info for this query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'get_amazon_product_details') 
                    {
                        if(isset($fun_args->query))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $asin = $fun_args->query;
                            if (empty($asin)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty search query provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['affiliate_id']) && trim($aiomatic_Chatbot_Settings['affiliate_id']) != '')
                            {
                                $aff_id = trim($aiomatic_Chatbot_Settings['affiliate_id']);
                            }
                            else
                            {
                                $aff_id = '';
                            }
                            if (isset($aiomatic_Chatbot_Settings['target_country']) && trim($aiomatic_Chatbot_Settings['target_country']) != '')
                            {
                                $target_country = trim($aiomatic_Chatbot_Settings['target_country']);
                            }
                            else
                            {
                                $target_country = 'com';
                            }
                            $max_prod = 1;
                            $amazresult = aiomatic_amazon_get_post($asin, trim($aff_id), $target_country, '', '', '', $max_prod, '1', array());
                            if(is_array($amazresult) && ((isset($amazresult['status']) && $amazresult['status'] == 'nothing') || count($amazresult) == 0))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No Amazon products found for query: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'An error occurred while search Amazon for: ' . $asin,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $final_result = 'Product title: ' . $amazresult[0]->offer_title . '\n';
                                $final_result .= 'Description: ' . $amazresult[0]->offer_desc . '\n';
                                $final_result .= 'URL: ' . $amazresult[0]->offer_url . '\n';
                                $final_result .= 'Price: ' . $amazresult[0]->offer_price . '\n';
                                $final_result .= 'Listing Price: ' . $amazresult[0]->product_list_price . '\n';
                                $final_result .= 'Image: ' . $amazresult[0]->offer_img . '\n';
                                $final_result .= 'Add to cart URL: ' . $amazresult[0]->cart_url . '\n';
                                $final_result .= 'Other images: ' . $amazresult[0]->product_imgs . '\n';
                                //new
                                if(!empty($amazresult[0]->item_score))
                                {
                                    $final_result .= 'Score: ' . $amazresult[0]->item_score . '\n';
                                }
                                if(!empty($amazresult[0]->language))
                                {
                                    $final_result .= 'Language: ' . $amazresult[0]->language . '\n';
                                }
                                if(!empty($amazresult[0]->edition))
                                {
                                    $final_result .= 'Edition: ' . $amazresult[0]->edition . '\n';
                                }
                                if(!empty($amazresult[0]->pages_count))
                                {
                                    $final_result .= 'Pages Count: ' . $amazresult[0]->pages_count . '\n';
                                }
                                if(!empty($amazresult[0]->publication_date))
                                {
                                    $final_result .= 'Date: ' . $amazresult[0]->publication_date . '\n';
                                }
                                if(!empty($amazresult[0]->contributors))
                                {
                                    $final_result .= 'Contributors: ' . $amazresult[0]->contributors . '\n';
                                }
                                if(!empty($amazresult[0]->manufacturer))
                                {
                                    $final_result .= 'Manufacturer: ' . $amazresult[0]->manufacturer . '\n';
                                }
                                if(!empty($amazresult[0]->binding))
                                {
                                    $final_result .= 'Binding: ' . $amazresult[0]->binding . '\n';
                                }
                                if(!empty($amazresult[0]->product_group))
                                {
                                    $final_result .= 'Product Group: ' . $amazresult[0]->product_group . '\n';
                                }
                                if(!empty($amazresult[0]->rating))
                                {
                                    $final_result .= 'Rating: ' . $amazresult[0]->rating . '\n';
                                }
                                if(!empty($amazresult[0]->eans))
                                {
                                    $final_result .= 'EAN: ' . $amazresult[0]->eans . '\n';
                                }
                                if(!empty($amazresult[0]->part_no))
                                {
                                    $final_result .= 'Part No: ' . $amazresult[0]->part_no . '\n';
                                }
                                if(!empty($amazresult[0]->model))
                                {
                                    $final_result .= 'Model: ' . $amazresult[0]->model . '\n';
                                }
                                if(!empty($amazresult[0]->warranty))
                                {
                                    $final_result .= 'Warranty: ' . $amazresult[0]->warranty . '\n';
                                }
                                if(!empty($amazresult[0]->color))
                                {
                                    $final_result .= 'Color: ' . $amazresult[0]->color . '\n';
                                }
                                if(!empty($amazresult[0]->is_adult))
                                {
                                    $final_result .= 'Is Adult: ' . $amazresult[0]->is_adult . '\n';
                                }
                                if(!empty($amazresult[0]->dimensions))
                                {
                                    $final_result .= 'Dimensions: ' . $amazresult[0]->dimensions . '\n';
                                }
                                if(!empty($amazresult[0]->size))
                                {
                                    $final_result .= 'Size: ' . $amazresult[0]->size . '\n';
                                }
                                if(!empty($amazresult[0]->unit_count))
                                {
                                    $final_result .= 'Unit Count: ' . $amazresult[0]->unit_count . '\n';
                                }
                                $final_result .= 'Reviews: ' . implode(PHP_EOL, $amazresult[0]->item_reviews) . '\n';
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'manage_booking_calendar_booking') 
                    {
                        if (!empty($fun_args->start_date) && !empty($fun_args->end_date) && !empty($fun_args->name) && !empty($fun_args->email)) 
                        {
                            $start_date  = sanitize_text_field($fun_args->start_date);
                            $end_date    = sanitize_text_field($fun_args->end_date);
                            $name        = sanitize_text_field($fun_args->name);
                            $email       = sanitize_email($fun_args->email);
                            $secondname  = isset($fun_args->secondname) ? sanitize_text_field($fun_args->secondname) : '';
                            $resource_id = isset($fun_args->resource_id) ? intval($fun_args->resource_id) : 1;

                            if (!function_exists('wpbc_api_is_dates_booked') || !function_exists('wpbc_api_booking_add_new')) {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Booking Calendar API functions are not available.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $dates = [$start_date, $end_date];
                            $params = ['is_use_booking_recurrent_time' => false];

                            $is_booked = wpbc_api_is_dates_booked($dates, $resource_id, $params);
                            if ($is_booked) {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'These dates are already booked, select different dates',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $data = [
                                'name'       => $name,
                                'email'      => ['value' => $email, 'type' => 'email'],
                                'secondname' => ['value' => $secondname, 'type' => 'text']
                            ];

                            $booking_id = wpbc_api_booking_add_new($dates, $data, $resource_id);

                            if ($booking_id) {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Booking created: ' . $booking_id,
                                    'assistant_message' => $as_mes
                                ));
                            } else {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to create booking.',
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Arguments not set for the booking function call.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }
                    }
                    elseif ($tool_call->name === 'aimogen_content_editor_templates') 
                    {
                        $operation = '';
                        if(isset($fun_args->operation))
                        {
                            $operation = $fun_args->operation;
                        }
                        $post_id = 0;
                        if(isset($fun_args->post_id))
                        {
                            $post_id = intval($fun_args->post_id);
                        }
                        $template_id = 0;
                        if(isset($fun_args->template_id))
                        {
                            $template_id = intval($fun_args->template_id);
                        }

                        if (empty($operation)) 
                        {
                            if(empty($post_id) || empty($template_id))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: operation parameter missing',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aimogen_content_editor_templates_list(),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($post_id <= 0) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid post_id',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $post_obj = get_post($post_id);
                            if (!$post_obj) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Post not found',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $template_to_run = 'skip';

                            if ($template_id > 0) 
                            {
                                $template_post = get_post($template_id);
                                if (!$template_post || $template_post->post_type !== 'aiomatic_editor_temp') 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Invalid template_id',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $template_to_run = $template_id;
                            }

                            aiomatic_do_post($post_obj, true, $template_to_run, false);

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $template_id > 0 ? 'Template applied successfully' : 'Executed with default template logic',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => 'Invalid operation',
                            'assistant_message' => $as_mes
                        ));
                    }
                    elseif ($tool_call->name === 'get_post_structure') 
                    {
                        $post_id = 0;

                        if(isset($fun_args->post_id))
                        {
                            $post_id = intval($fun_args->post_id);
                        }

                        if ($post_id <= 0) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: post_id is required',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $post = get_post($post_id);

                        if (!$post) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Post not found',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $content = $post->post_content;

                        if (empty($content)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: Empty content',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $blocks = function_exists('parse_blocks') ? parse_blocks($content) : [];
                        $html   = !empty($blocks) ? render_block_data_recursive($blocks) : $content;

                        if (empty($html)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: Failed to normalize content',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        libxml_use_internal_errors(true);

                        $dom = new DOMDocument();

                        $loaded = $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

                        libxml_clear_errors();

                        if (!$loaded) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: Failed parsing HTML',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $xpath = new DOMXPath($dom);

                        $structure = [];

                        $headings = $xpath->query('//h2 | //h3 | //h4');

                        if ($headings) 
                        {
                            foreach ($headings as $node) 
                            {
                                $text = trim(preg_replace('/\s+/', ' ', $node->textContent));

                                if ($text === '') {
                                    continue;
                                }

                                $type = strtolower($node->nodeName);

                                $structure[] = [
                                    'type'     => $type,
                                    'text'     => $text,
                                    'selector' => $type . ':' . $text
                                ];
                            }
                        }

                        $paragraphs = $xpath->query('//p');
                        $paragraph_count = ($paragraphs) ? $paragraphs->length : 0;

                        $suggested = array_map(function($s){
                            return $s['selector'];
                        }, $structure);

                        array_unshift($suggested, 'first_paragraph');
                        $suggested[] = 'last_paragraph';

                        $suggested = array_values(array_unique($suggested));

                        $result = wp_json_encode([
                            'total_paragraphs'    => $paragraph_count,
                            'total_sections'      => count($structure),
                            'sections'            => $structure,
                            'suggested_selectors' => $suggested
                        ]);

                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => $result,
                            'assistant_message' => $as_mes
                        ));

                        continue;
                    }
                    elseif ($tool_call->name === 'edit_post_section') 
                    {
                        $post_id     = isset($fun_args->post_id) ? intval($fun_args->post_id) : 0;
                        $selector    = isset($fun_args->section_selector) ? sanitize_text_field($fun_args->section_selector) : '';
                        $instruction = isset($fun_args->instruction) ? trim(wp_kses_post($fun_args->instruction)) : '';

                        if ($post_id <= 0 || $selector === '' || $instruction === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: post_id, section_selector and instruction are required.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $post = get_post($post_id);

                        if (!$post) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Post with ID " . $post_id . " not found.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $content = $post->post_content;

                        if (trim($content) === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Post content is empty.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $blocks          = function_exists('parse_blocks') ? parse_blocks($content) : array();
                        $is_block_editor = function_exists('has_blocks') ? has_blocks($content) : !empty($blocks);
                        $html            = ($is_block_editor && function_exists('render_block_data_recursive')) ? render_block_data_recursive($blocks) : $content;

                        if (trim($html) === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to prepare post HTML.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        libxml_use_internal_errors(true);

                        $dom = new DOMDocument('1.0', 'UTF-8');

                        $loaded = $dom->loadHTML(
                            '<?xml encoding="utf-8" ?><html><body>' . $html . '</body></html>',
                            LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
                        );

                        libxml_clear_errors();

                        if (!$loaded) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to parse post HTML.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $body = $dom->getElementsByTagName('body')->item(0);

                        if (!$body) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to locate parsed HTML body.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $xpath       = new DOMXPath($dom);
                        $target_node = null;

                        if ($selector === 'full_content') 
                        {
                            $target_node = $body;
                        }
                        elseif ($selector === 'first_paragraph') 
                        {
                            $nodes = $xpath->query('//p');
                            if ($nodes && $nodes->length > 0) {
                                $target_node = $nodes->item(0);
                            }
                        }
                        elseif ($selector === 'last_paragraph') 
                        {
                            $nodes = $xpath->query('//p');
                            if ($nodes && $nodes->length > 0) {
                                $target_node = $nodes->item($nodes->length - 1);
                            }
                        }
                        elseif (strpos($selector, 'paragraph:') === 0) 
                        {
                            $num   = max(0, ((int) str_replace('paragraph:', '', $selector)) - 1);
                            $nodes = $xpath->query('//p');

                            if ($nodes && $nodes->length > $num) {
                                $target_node = $nodes->item($num);
                            }
                        }
                        elseif (preg_match('/^h([2-4]):(.+)$/', $selector, $m)) 
                        {
                            $tag  = 'h' . $m[1];
                            $text = trim($m[2]);

                            $nodes = $xpath->query('//' . $tag);

                            if ($nodes) 
                            {
                                foreach ($nodes as $node) 
                                {
                                    if (stripos(trim($node->textContent), $text) !== false) 
                                    {
                                        $target_node = $node;
                                        break;
                                    }
                                }
                            }
                        }

                        if (!$target_node) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Could not locate section for selector '" . $selector . "'.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        if ($selector === 'full_content') 
                        {
                            $target_html = '';

                            foreach ($body->childNodes as $child) {
                                $target_html .= $dom->saveHTML($child);
                            }
                        } 
                        else 
                        {
                            $target_html = $dom->saveHTML($target_node);
                        }

                        if (trim($target_html) === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed extracting target content.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $prompt = "You are editing HTML content.

                    STRICT RULES:
                    - Do NOT remove any existing content unless the instruction clearly asks for it
                    - Do NOT shorten text unless the instruction clearly asks for it
                    - Do NOT remove links or formatting
                    - Keep all HTML tags valid
                    - Return valid HTML only
                    - Do NOT add explanations or comments

                    Instruction:
                    {$instruction}

                    === ORIGINAL CONTENT START ===
                    {$target_html}
                    === ORIGINAL CONTENT END ===

                    Return ONLY the edited HTML.";

                        $model = $this->model;

                        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
                        $appids = array();

                        if (is_array($aiomatic_Main_Settings) && !empty($aiomatic_Main_Settings['app_id'])) {
                            $appids = array_filter(preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id'])));
                        }

                        $token = !empty($appids) ? $appids[array_rand($appids)] : '';
                        $token = apply_filters('aiomatic_openai_api_key', $token);

                        if (empty($token)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: OpenAI API key is missing.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $query_token_count = count(aiomatic_encode($prompt));
                        $max_tokens        = aimogenpro_get_max_tokens($model);

                        $available_tokens = aiomatic_compute_available_tokens(
                            $model,
                            $max_tokens,
                            $prompt,
                            $query_token_count
                        );

                        if ($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) 
                        {
                            $cut = intval(aiomatic_strlen($prompt) / 2);
                            $prompt = trim(aiomatic_substr($prompt, 0, -$cut));

                            $query_token_count = count(aiomatic_encode($prompt));
                            $available_tokens  = $max_tokens - $query_token_count;
                        }

                        if ($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Not enough available tokens to edit this section.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $thread_id     = '';
                        $aierror       = '';
                        $finish_reason = '';

                        $edited = aiomatic_generate_text(
                            $token,
                            $model,
                            $prompt,
                            $available_tokens,
                            0.2,
                            1,
                            0,
                            0,
                            false,
                            'agentsEdit',
                            0,
                            $finish_reason,
                            $aierror,
                            false,
                            false,
                            false,
                            '',
                            '',
                            'user',
                            '',
                            $thread_id,
                            '',
                            'disabled',
                            '',
                            false,
                            false,
                            array(),
                            '',
                            '',
                            ''
                        );

                        if (!empty($aierror)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: AI error - " . $aierror,
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        if (empty($edited)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: AI returned empty result.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $edited = trim($edited);

                        $edited = preg_replace('/^\s*```(?:html)?\s*/i', '', $edited);
                        $edited = preg_replace('/\s*```\s*$/', '', $edited);
                        $edited = preg_replace('#</?(?:html|body)[^>]*>#i', '', $edited);

                        $edited = trim($edited);

                        if ($edited === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: AI returned empty HTML after cleanup.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $fragment = $dom->createDocumentFragment();

                        if (!@$fragment->appendXML($edited)) 
                        {
                            $tmp = new DOMDocument('1.0', 'UTF-8');

                            libxml_use_internal_errors(true);

                            $tmp_loaded = $tmp->loadHTML(
                                '<?xml encoding="utf-8" ?><html><body><div id="aiomatic_tmp_wrapper">' . $edited . '</div></body></html>',
                                LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
                            );

                            libxml_clear_errors();

                            if (!$tmp_loaded) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Invalid HTML returned by AI.",
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $tmp_xpath = new DOMXPath($tmp);
                            $wrapper   = $tmp_xpath->query('//*[@id="aiomatic_tmp_wrapper"]')->item(0);

                            if (!$wrapper) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Could not parse edited HTML wrapper.",
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            foreach ($wrapper->childNodes as $child) 
                            {
                                $fragment->appendChild($dom->importNode($child, true));
                            }

                            if (!$fragment->hasChildNodes()) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Edited HTML contains no usable nodes.",
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }

                        if ($selector === 'full_content') 
                        {
                            while ($body->firstChild) {
                                $body->removeChild($body->firstChild);
                            }

                            $body->appendChild($fragment);
                        }
                        else 
                        {
                            if (!$target_node->parentNode) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Target node has no parent.",
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $target_node->parentNode->replaceChild($fragment, $target_node);
                        }

                        $body = $dom->getElementsByTagName('body')->item(0);

                        if (!$body) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Failed to rebuild post HTML body.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $new_html = '';

                        foreach ($body->childNodes as $child) {
                            $new_html .= $dom->saveHTML($child);
                        }

                        $new_html = trim($new_html);

                        if ($new_html === '') 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error: Edited content became empty. Update cancelled.",
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        if ($is_block_editor) {
                            $new_content = "<!-- wp:html -->\n" . $new_html . "\n<!-- /wp:html -->";
                        } else {
                            $new_content = $new_html;
                        }

                        $updated = wp_update_post(array(
                            'ID'           => $post_id,
                            'post_content' => $new_content
                        ), true);

                        if (is_wp_error($updated)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Error updating post: " . $updated->get_error_message(),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => "Success: post ID " . $post_id . " updated.",
                            'assistant_message' => $as_mes
                        ));
                    }
                    elseif ($tool_call->name === 'list_available_ai_agents') 
                    {
                        $agents_query = new WP_Query(array(
                            'post_type' => 'aiomatic_agent',
                            'post_status' => 'publish',
                            'posts_per_page' => -1,
                        ));

                        $agents = array();

                        if ($agents_query->have_posts()) 
                        {
                            $all_tools = Aiomatic_Agent::get_agent_tools();
                            $all_tool_names = array_keys($all_tools);
                            while ($agents_query->have_posts()) 
                            {
                                $agents_query->the_post();

                                $id = get_the_ID();
                                if ((int)$id === (int)$agent->get_agent_id())
                                {
                                    continue;
                                }
                                $config = get_post_meta($id, '_agent_config', true);
                                $allowed_tools = [];

                                if (is_array($config)) {
                                    if (
                                        array_key_exists('allowed_tools', $config) &&
                                        is_array($config['allowed_tools']) &&
                                        !empty($config['allowed_tools'])
                                    ) {
                                        $allowed_tools = array_values($config['allowed_tools']);
                                    } else {
                                        $allowed_tools = $all_tool_names;
                                    }
                                } else {
                                    $allowed_tools = $all_tool_names;
                                }
                                $allowed_tools = array_values(array_intersect($allowed_tools, $all_tool_names));
                                $agents[] = array(
                                    'agent_id' => $id,
                                    'agent_name' => get_the_title(),
                                    'description' => get_post_meta($id, 'aiomatic_agent_description', true),
                                    'expertise' => get_post_meta($id, 'aiomatic_agent_expertise', true),
                                    'tools'       => $allowed_tools,
                                    'capabilities' => [
                                        'can_publish' => (in_array('manage_wp_post', $allowed_tools) || in_array('edit_post_section', $allowed_tools)),
                                        'can_research' => in_array('google_results_parser', $allowed_tools),
                                        'can_scrape' => in_array('website_scraper', $allowed_tools),
                                        'can_email' => in_array('wp_send_email', $allowed_tools),
                                    ],
                                    'max_steps' => isset($config['max_steps']) ? intval($config['max_steps']) : 20,
                                    'model' => get_post_meta($id, '_model', true),
                                );
                            }
                            wp_reset_postdata();
                        }

                        if (empty($agents)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'No agents found',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => wp_json_encode($agents),
                            'assistant_message' => $as_mes
                        ));
                    }
                    elseif ($tool_call->name === 'delegate_to_ai_agent') 
                    {
                        $za_conf = $agent->get_config();

                        // Delegation disabled
                        if (empty($za_conf['allow_delegation'])) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Delegation disabled",
                                    "instruction" => "You are not allowed to delegate tasks. Continue solving the task yourself."
                                ]),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        // Prevent sub-agent chaining
                        if ($agent->get_is_sub_agent()) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Sub-agents cannot delegate",
                                    "instruction" => "Complete the task directly without further delegation."
                                ]),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        // Validate arguments existence
                        if (!isset($fun_args->agent_id) || !isset($fun_args->task))
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Missing required parameters",
                                    "required" => ["agent_id", "task"],
                                    "instruction" => "Call list_available_ai_agents first, choose a valid agent_id, then call delegate_to_ai_agent again with both agent_id and task."
                                ]),
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Invalid delegate call (missing params): ' . print_r($tool_call, true));
                            continue;
                        }

                        $agent_id = trim($fun_args->agent_id);
                        $task     = trim($fun_args->task);

                        // Validate non-empty values
                        if ($agent_id === '' || $task === '')
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Empty parameters",
                                    "instruction" => "agent_id and task must not be empty. Retrieve agent_id using list_available_ai_agents and retry."
                                ]),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        // Prevent self-delegation
                        if ((int)$agent_id === (int)$agent->get_agent_id()) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Invalid delegation target",
                                    "instruction" => "You cannot delegate to yourself. Choose a different agent_id from list_available_ai_agents."
                                ]),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        // Execute delegation
                        $res = $agent->aiomatic_call_agent($agent_id, $task);

                        if (!empty($res)) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $res,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => json_encode([
                                    "error" => "Agent execution failed",
                                    "instruction" => "Retry delegation or choose a different agent."
                                ]),
                                'assistant_message' => $as_mes
                            ));
                        }
                    }
                    elseif ($tool_call->name === 'read_server_file') 
                    {
                        if(isset($fun_args->file_path))
                        {
                            $file_path = $fun_args->file_path;

                            $base_dir = WP_CONTENT_DIR;
                            $real_path = realpath(ABSPATH . ltrim($file_path, '/\\'));

                            if (!$real_path || strpos($real_path, $base_dir) !== 0) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Access denied',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $ext = pathinfo($real_path, PATHINFO_EXTENSION);
                            if (!in_array($ext, array('txt', 'log', 'csv', 'json'))) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid file type',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if (!file_exists($real_path)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'File not found',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            $content = substr($wp_filesystem->get_contents($real_path), 0, 5000);

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $content,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'file_path parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'write_server_file') 
                    {
                        if(isset($fun_args->filename) && isset($fun_args->content))
                        {
                            $filename  = $fun_args->filename;
                            $content   = $fun_args->content;
                            $overwrite = isset($fun_args->overwrite) ? (bool)$fun_args->overwrite : false;

                            // 1. Base sandbox directory
                            $upload_dir = wp_upload_dir();
                            $base_dir   = trailingslashit($upload_dir['basedir']) . 'aiomatic-exports/';

                            if (!file_exists($base_dir)) {
                                wp_mkdir_p($base_dir);
                            }

                            // Optional hardening
                            if (!file_exists($base_dir . 'index.php')) {
                                @file_put_contents($base_dir . 'index.php', "<?php\n// Silence is golden.\n");
                            }

                            // 2. Sanitize filename
                            $filename = sanitize_file_name($filename);

                            if (empty($filename) || basename($filename) !== $filename)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid filename',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // 3. Extension validation
                            $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                            $allowed = array('txt','log','csv','json','md');

                            if (empty($ext) || !in_array($ext, $allowed, true))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid file type',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // 4. Size limit
                            if (strlen($content) > 2 * 1024 * 1024)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Content too large (max 2MB)',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // 5. Safe path
                            $target_path = $base_dir . $filename;

                            $real_base = realpath($base_dir);
                            $real_target_dir = realpath(dirname($target_path));

                            if (!$real_base || !$real_target_dir || strpos($real_target_dir, $real_base) !== 0)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid write path',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // 6. Prevent overwrite
                            if (file_exists($target_path) && !$overwrite)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'File exists (overwrite not allowed)',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // 7. JSON validation
                            if ($ext === 'json')
                            {
                                json_decode($content, true);
                                if (json_last_error() !== JSON_ERROR_NONE)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Invalid JSON content',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }

                            // 8. Write
                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            $bytes = $wp_filesystem->put_contents($target_path, $content, LOCK_EX);

                            if ($bytes === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to write file',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            aiomatic_log_to_file('Agent wrote file: ' . $target_path);

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Success: File saved as ' . basename($target_path),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'filename or content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'get_wp_post_data') 
                    {
                        if(isset($fun_args->post_id))
                        {
                            $post_id = $fun_args->post_id;

                            if (empty($post_id)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: No Post ID provided.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $post = get_post($post_id);
                            if (!$post) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Error: Post with ID $post_id not found.",
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $clean_content = wp_strip_all_tags(strip_shortcodes($post->post_content));

                            $final_output = "Post ID: $post_id\n";
                            $final_output .= "Title: {$post->post_title}\n";
                            $final_output .= "Status: {$post->post_status}\n";
                            $final_output .= "Type: {$post->post_type}\n";
                            $final_output .= "Excerpt: {$post->post_excerpt}\n";
                            $final_output .= "--- CONTENT START ---\n";
                            $final_output .= $clean_content;
                            $final_output .= "\n--- CONTENT END ---";

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aiomatic_substr($final_output, 0, 45000),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'post_id parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'process_and_transform_data') 
                    {
                        if(isset($fun_args->operation) && isset($fun_args->input))
                        {
                            $operation = $fun_args->operation;
                            $input     = $fun_args->input;

                            if (empty($operation) || empty($input)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: operation and input are required.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $decoded = json_decode($input, true);

                            switch ($operation) 
                            {
                                case 'parse_json':

                                    if ($decoded === null) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Invalid JSON.',
                                            'assistant_message' => $as_mes
                                        ));
                                        continue 2;
                                    }

                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($decoded),
                                        'assistant_message' => $as_mes
                                    ));
                                    break;

                                case 'stringify_json':

                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($input),
                                        'assistant_message' => $as_mes
                                    ));
                                    break;

                                case 'list_keys':

                                    if (!is_array($decoded)) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Input must be JSON object or array.',
                                            'assistant_message' => $as_mes
                                        ));
                                        continue 2;
                                    }

                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => implode(', ', array_keys($decoded)),
                                        'assistant_message' => $as_mes
                                    ));
                                    break;

                                case 'extract_field':

                                    if(!isset($fun_args->field))
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: field parameter required.',
                                            'assistant_message' => $as_mes
                                        ));
                                        continue 2;
                                    }

                                    $field = $fun_args->field;

                                    if (!is_array($decoded)) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Input must be JSON.',
                                            'assistant_message' => $as_mes
                                        ));
                                        continue 2;
                                    }

                                    if (isset($decoded[$field])) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => json_encode($decoded[$field]),
                                            'assistant_message' => $as_mes
                                        ));
                                    }
                                    else
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: field not found.',
                                            'assistant_message' => $as_mes
                                        ));
                                    }
                                    break;

                                case 'filter_equals':

                                    if(!isset($fun_args->field))
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: field parameter required.',
                                            'assistant_message' => $as_mes
                                        ));
                                        continue 2;
                                    }

                                    $field = $fun_args->field;
                                    $value = isset($fun_args->value) ? $fun_args->value : '';

                                    if (!is_array($decoded)) 
                                    {
                                        aiomatic_agent_add_tool_results($reply, array(
                                            "tool_call_id" => $tool_call->id,
                                            "role" => "tool",
                                            "content" => 'Error: Input must be JSON array.',
                                            'assistant_message' => $as_mes
                                        ));
                                        continue 2;
                                    }

                                    $filtered = array();

                                    foreach ($decoded as $item) 
                                    {
                                        if (is_array($item) && isset($item[$field]) && (string)$item[$field] === (string)$value) 
                                        {
                                            $filtered[] = $item;
                                        }
                                    }

                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($filtered),
                                        'assistant_message' => $as_mes
                                    ));
                                    break;

                                default:

                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: Unknown operation.',
                                        'assistant_message' => $as_mes
                                    ));
                                    break;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'operation or input parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'pause_execution') 
                    {
                        if(isset($fun_args->seconds))
                        {
                            $seconds = (int)$fun_args->seconds;

                            if ($seconds <= 0) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: seconds must be greater than 0.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // safety cap
                            if ($seconds > 30) 
                            {
                                $seconds = 30;
                            }

                            sleep($seconds);

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Waited $seconds seconds.",
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'seconds parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'wp_validate_post_state') 
                    {
                        if(isset($fun_args->post_id) && isset($fun_args->checks))
                        {
                            $post_id = $fun_args->post_id;
                            $checks  = $fun_args->checks;

                            if (empty($post_id)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: post_id is required.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if (!is_array($checks) || empty($checks)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: checks must be a non-empty array.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $post = get_post($post_id);

                            $results = array();
                            $all_passed = true;

                            if (in_array('exists', $checks, true)) 
                            {
                                if ($post) {
                                    $results[] = "exists: PASS";
                                } else {
                                    $results[] = "exists: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (!$post) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => implode("\n", $results),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if (in_array('has_excerpt', $checks, true)) 
                            {
                                if (!empty($post->post_excerpt)) {
                                    $results[] = "has_excerpt: PASS";
                                } else {
                                    $results[] = "has_excerpt: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('has_featured_image', $checks, true)) 
                            {
                                if (get_post_thumbnail_id($post_id)) {
                                    $results[] = "has_featured_image: PASS";
                                } else {
                                    $results[] = "has_featured_image: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('has_content', $checks, true)) 
                            {
                                $clean = trim(wp_strip_all_tags($post->post_content));
                                if (!empty($clean)) {
                                    $results[] = "has_content: PASS";
                                } else {
                                    $results[] = "has_content: FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('content_length', $checks, true)) 
                            {
                                $min = isset($fun_args->min_content_length) ? (int)$fun_args->min_content_length : 100;
                                $len = strlen(wp_strip_all_tags($post->post_content));

                                if ($len >= $min) {
                                    $results[] = "content_length($len >= $min): PASS";
                                } else {
                                    $results[] = "content_length($len < $min): FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('status', $checks, true)) 
                            {
                                $expected = isset($fun_args->expected_status) ? $fun_args->expected_status : '';
                                if (!empty($expected) && $post->post_status === $expected) {
                                    $results[] = "status({$post->post_status}): PASS";
                                } else {
                                    $results[] = "status({$post->post_status}): FAIL";
                                    $all_passed = false;
                                }
                            }

                            if (in_array('has_terms', $checks, true)) 
                            {
                                $taxonomy = isset($fun_args->taxonomy) ? $fun_args->taxonomy : '';

                                if (empty($taxonomy)) 
                                {
                                    $results[] = "has_terms: FAIL (taxonomy missing)";
                                    $all_passed = false;
                                } 
                                else 
                                {
                                    $terms = get_the_terms($post_id, $taxonomy);
                                    if (!empty($terms) && !is_wp_error($terms)) {
                                        $results[] = "has_terms($taxonomy): PASS";
                                    } else {
                                        $results[] = "has_terms($taxonomy): FAIL";
                                        $all_passed = false;
                                    }
                                }
                            }

                            $summary = $all_passed ? "ALL CHECKS PASSED" : "SOME CHECKS FAILED";
                            $output = $summary . "\n\n" . implode("\n", $results);

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $output,
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'post_id or checks parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'wp_taxonomy_discovery') 
                    {
                        if(isset($fun_args->operation))
                        {
                            $operation = $fun_args->operation;

                            if (empty($operation)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: operation parameter was not provided.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if (!in_array($operation, array('list_taxonomies','list_terms','get_post_terms','create_term','set_post_terms'), true))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: Invalid operation parameter provided.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            // LIST TAXONOMIES
                            if ($operation === 'list_taxonomies')
                            {
                                $taxonomies = get_taxonomies(array(), 'objects');

                                if (empty($taxonomies))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No taxonomies found on this site.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $results = array();

                                foreach ($taxonomies as $taxonomy)
                                {
                                    $results[] = sprintf(
                                        "Name: %s | Label: %s | Public: %s | Hierarchical: %s | Object Types: %s",
                                        $taxonomy->name,
                                        $taxonomy->label,
                                        !empty($taxonomy->public) ? 'yes' : 'no',
                                        !empty($taxonomy->hierarchical) ? 'yes' : 'no',
                                        !empty($taxonomy->object_type) ? implode(',', $taxonomy->object_type) : '-'
                                    );
                                }

                                $output = "Available Taxonomies:\n\n" . implode("\n---\n", $results);

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => aiomatic_substr($output, 0, 45000),
                                    'assistant_message' => $as_mes
                                ));
                            }

                            // LIST TERMS
                            elseif ($operation === 'list_terms')
                            {
                                if(!isset($fun_args->taxonomy))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy parameter not found',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $taxonomy = $fun_args->taxonomy;

                                if (!taxonomy_exists($taxonomy))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "Error: Taxonomy $taxonomy does not exist.",
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $terms = get_terms(array(
                                    'taxonomy' => $taxonomy,
                                    'hide_empty' => false,
                                    'number' => 20
                                ));

                                if (is_wp_error($terms) || empty($terms))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "No terms found for taxonomy: $taxonomy",
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $results = array();

                                foreach ($terms as $term)
                                {
                                    $results[] = sprintf(
                                        "ID: %d | Name: %s | Slug: %s | Count: %d",
                                        $term->term_id,
                                        $term->name,
                                        $term->slug,
                                        $term->count
                                    );
                                }

                                $output = "Terms for taxonomy '$taxonomy':\n\n" . implode("\n---\n", $results);

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => aiomatic_substr($output, 0, 45000),
                                    'assistant_message' => $as_mes
                                ));
                            }

                            // GET POST TERMS
                            elseif ($operation === 'get_post_terms')
                            {
                                if(!isset($fun_args->taxonomy) || !isset($fun_args->post_id))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy or post_id parameter missing',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $taxonomy = $fun_args->taxonomy;
                                $post_id  = $fun_args->post_id;

                                $terms = get_the_terms($post_id, $taxonomy);

                                if (empty($terms) || is_wp_error($terms))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "No terms assigned.",
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $results = array();

                                foreach ($terms as $term)
                                {
                                    $results[] = sprintf(
                                        "ID: %d | Name: %s | Slug: %s",
                                        $term->term_id,
                                        $term->name,
                                        $term->slug
                                    );
                                }

                                $output = implode("\n", $results);

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $output,
                                    'assistant_message' => $as_mes
                                ));
                            }

                            // CREATE TERM
                            elseif ($operation === 'create_term')
                            {
                                if(!isset($fun_args->taxonomy) || !isset($fun_args->term_name))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy or term_name missing',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $taxonomy = $fun_args->taxonomy;
                                $term_name = $fun_args->term_name;

                                $existing = term_exists($term_name, $taxonomy);

                                if ($existing)
                                {
                                    $term_id = is_array($existing) ? $existing['term_id'] : $existing;

                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "Term already exists. ID: $term_id",
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $created = wp_insert_term($term_name, $taxonomy);

                                if (is_wp_error($created))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => $created->get_error_message(),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Created term ID: " . $created['term_id'],
                                    'assistant_message' => $as_mes
                                ));
                            }
                            elseif ($operation === 'set_post_terms')
                            {
                                if(
                                    !isset($fun_args->taxonomy) ||
                                    !isset($fun_args->post_id) ||
                                    !isset($fun_args->term_name)
                                )
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'taxonomy, post_id or term_name missing',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $taxonomy = sanitize_text_field($fun_args->taxonomy);
                                $post_id  = intval($fun_args->post_id);
                                $terms    = sanitize_text_field($fun_args->term_name);

                                if (empty($taxonomy) || $post_id <= 0 || empty($terms))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Invalid taxonomy, post_id or term_name',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                if (!taxonomy_exists($taxonomy))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "Taxonomy $taxonomy does not exist",
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $term_names = array_map('trim', explode(',', $terms));
                                $term_ids   = [];

                                foreach ($term_names as $name)
                                {
                                    if ($name === '') continue;

                                    $existing = term_exists($name, $taxonomy);

                                    if (!$existing)
                                    {
                                        $created = wp_insert_term($name, $taxonomy);

                                        if (is_wp_error($created))
                                        {
                                            continue;
                                        }

                                        $term_ids[] = (int)$created['term_id'];
                                    }
                                    else
                                    {
                                        $term_ids[] = is_array($existing) ? (int)$existing['term_id'] : (int)$existing;
                                    }
                                }

                                if (empty($term_ids))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => "No valid terms to assign",
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                wp_set_post_terms($post_id, $term_ids, $taxonomy, false);

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Success: Assigned " . count($term_ids) . " terms to post $post_id",
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'operation parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'get_environment_info') 
                    {
                        if(isset($fun_args->info_type))
                        {
                            $type = sanitize_text_field($fun_args->info_type);

                            $allowed = array('general','plugins','theme','stats','capabilities','post_types','taxonomies','all');

                            if (!in_array($type, $allowed, true)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: Invalid info_type parameter.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $output = "Site Context Snapshot\n\n";

                            if ($type === 'general' || $type === 'all') 
                            {
                                $output .= "--- GENERAL ---\n";
                                $output .= "Site URL: " . site_url() . "\n";
                                $output .= "Home URL: " . home_url() . "\n";
                                $output .= "Name: " . get_bloginfo('name') . "\n";
                                $output .= "Description: " . get_bloginfo('description') . "\n";
                                $output .= "Admin Email: " . get_bloginfo('admin_email') . "\n";
                                $output .= "Language: " . get_bloginfo('language') . "\n";
                                $output .= "WP Version: " . get_bloginfo('version') . "\n\n";
                            }

                            if ($type === 'theme' || $type === 'all') 
                            {
                                $theme = wp_get_theme();

                                $output .= "--- THEME ---\n";
                                $output .= "Name: " . $theme->get('Name') . "\n";
                                $output .= "Version: " . $theme->get('Version') . "\n";
                                $output .= "Author: " . $theme->get('Author') . "\n\n";
                            }

                            if ($type === 'plugins' || $type === 'all' || $type === 'capabilities') 
                            {
                                if (!function_exists('get_plugins')) {
                                    require_once ABSPATH . 'wp-admin/includes/plugin.php';
                                }

                                $active_plugins = get_option('active_plugins', array());
                                $all_plugins = get_plugins();

                                if ($type === 'plugins' || $type === 'all') 
                                {
                                    $output .= "--- ACTIVE PLUGINS ---\n";

                                    if (!empty($active_plugins)) {
                                        foreach ($active_plugins as $plugin_file) {
                                            if (isset($all_plugins[$plugin_file])) {
                                                $output .= "- " . $all_plugins[$plugin_file]['Name'] . " (v" . $all_plugins[$plugin_file]['Version'] . ")\n";
                                            }
                                        }
                                    } else {
                                        $output .= "No active plugins found.\n";
                                    }

                                    $output .= "\n";
                                }
                            }

                            if ($type === 'stats' || $type === 'all') 
                            {
                                $posts    = (int)(wp_count_posts('post')->publish ?? 0);
                                $pages    = (int)(wp_count_posts('page')->publish ?? 0);
                                $products = post_type_exists('product') ? (int)(wp_count_posts('product')->publish ?? 0) : 0;
                                $users    = (int)(count_users()['total_users'] ?? 0);

                                $output .= "--- STATS ---\n";
                                $output .= "Posts: $posts\n";
                                $output .= "Pages: $pages\n";
                                $output .= "Products: $products\n";
                                $output .= "Users: $users\n\n";
                            }

                            if ($type === 'post_types' || $type === 'all') 
                            {
                                $cpts = get_post_types(array('public' => true), 'objects');

                                $output .= "--- POST TYPES ---\n";
                                foreach ($cpts as $pt) {
                                    $output .= "- {$pt->name} ({$pt->label})\n";
                                }
                                $output .= "\n";
                            }

                            if ($type === 'taxonomies' || $type === 'all') 
                            {
                                $taxes = get_taxonomies(array('public' => true), 'objects');

                                $output .= "--- TAXONOMIES ---\n";
                                foreach ($taxes as $tx) {
                                    $output .= "- {$tx->name} ({$tx->label}) | used on: " . implode(',', $tx->object_type) . "\n";
                                }
                                $output .= "\n";
                            }

                            if ($type === 'capabilities' || $type === 'all') 
                            {
                                $output .= "--- CAPABILITIES ---\n";

                                $output .= "WooCommerce: " . (class_exists('WooCommerce') ? 'yes' : 'no') . "\n";
                                $output .= "Elementor: " . (defined('ELEMENTOR_VERSION') ? 'yes' : 'no') . "\n";
                                $output .= "Gutenberg: " . (function_exists('register_block_type') ? 'yes' : 'no') . "\n";
                                $output .= "REST API: " . (function_exists('register_rest_route') ? 'yes' : 'no') . "\n";

                                $output .= "ACF: " . (class_exists('ACF') ? 'yes' : 'no') . "\n";
                                $output .= "Custom Fields: " . (post_type_supports('post', 'custom-fields') ? 'yes' : 'no') . "\n";
                                $output .= "Featured Images: " . (current_theme_supports('post-thumbnails') ? 'yes' : 'no') . "\n";

                                $output .= "SEO Plugins:\n";
                                $output .= "- Yoast: " . (defined('WPSEO_VERSION') ? 'yes' : 'no') . "\n";
                                $output .= "- RankMath: " . (defined('RANK_MATH_VERSION') ? 'yes' : 'no') . "\n";
                                $output .= "- AIOSEO: " . (defined('AIOSEO_VERSION') ? 'yes' : 'no') . "\n";

                                $output .= "\n";
                            }

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aiomatic_substr(trim($output), 0, 45000),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'info_type parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'manage_wp_post') 
                    {
                        if (!isset($fun_args->operation) || empty($fun_args->operation))
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'operation parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: operation missing - ' . print_r($tool_call, true));
                            continue;
                        }

                        $operation = sanitize_text_field($fun_args->operation);

                        $allowed_operations = array(
                            'create','update','trash','untrash','delete','duplicate',
                            'append_content','prepend_content','set_featured_image',
                            'delete_featured_image','set_meta','delete_meta','set_terms'
                        );

                        if (!in_array($operation, $allowed_operations, true))
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: Invalid operation. Allowed operations are: ' . implode(', ', $allowed_operations),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        // --- CREATE ---
                        if ($operation === 'create')
                        {
                            if (empty($fun_args->post_title) || empty($fun_args->post_content))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: Both post_title and post_content are required.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $post_data = array(
                                'post_title'      => wp_strip_all_tags($fun_args->post_title),
                                'post_content'    => $fun_args->post_content,
                                'post_status'     => $fun_args->post_status ?? 'draft',
                                'post_type'       => $fun_args->post_type ?? 'post',
                                'post_excerpt'    => $fun_args->post_excerpt ?? '',
                                'post_name'       => isset($fun_args->post_name) ? sanitize_title($fun_args->post_name) : '',
                                'post_parent'     => isset($fun_args->post_parent) ? intval($fun_args->post_parent) : 0,
                                'menu_order'      => isset($fun_args->menu_order) ? intval($fun_args->menu_order) : 0,
                                'comment_status'  => $fun_args->comment_status ?? 'closed',
                                'ping_status'     => $fun_args->ping_status ?? 'closed',
                            );

                            $new_post_id = wp_insert_post($post_data, true);

                            if (is_wp_error($new_post_id))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: ' . $new_post_id->get_error_message(),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if (!empty($fun_args->featured_image_id))
                            {
                                set_post_thumbnail($new_post_id, intval($fun_args->featured_image_id));
                            }

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Success: Post created. ID: $new_post_id. URL: " . get_permalink($new_post_id),
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        // --- IDS ---
                        $post_ids = array();

                        if (!empty($fun_args->post_ids))
                        {
                            $post_ids = array_map('intval', array_filter(array_map('trim', explode(',', $fun_args->post_ids))));
                        }
                        elseif (!empty($fun_args->ID))
                        {
                            $post_ids = array(intval($fun_args->ID));
                        }

                        if (empty($post_ids))
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Error: ID or post_ids required.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }

                        $results = array();

                        foreach ($post_ids as $post_id)
                        {
                            $existing_post = get_post($post_id);

                            if (!$existing_post)
                            {
                                $results[] = "Error: Post $post_id not found.";
                                continue;
                            }

                            // --- UPDATE ---
                            if ($operation === 'update')
                            {
                                $post_data = array('ID' => $post_id);

                                if (isset($fun_args->post_title)) $post_data['post_title'] = wp_strip_all_tags($fun_args->post_title);
                                if (isset($fun_args->post_content)) $post_data['post_content'] = $fun_args->post_content;
                                if (isset($fun_args->post_status)) $post_data['post_status'] = $fun_args->post_status;
                                if (isset($fun_args->post_type)) $post_data['post_type'] = $fun_args->post_type;
                                if (isset($fun_args->post_excerpt)) $post_data['post_excerpt'] = $fun_args->post_excerpt;
                                if (isset($fun_args->post_name)) $post_data['post_name'] = sanitize_title($fun_args->post_name);
                                if (isset($fun_args->post_parent)) $post_data['post_parent'] = intval($fun_args->post_parent);
                                if (isset($fun_args->menu_order)) $post_data['menu_order'] = intval($fun_args->menu_order);
                                if (isset($fun_args->comment_status)) $post_data['comment_status'] = $fun_args->comment_status;
                                if (isset($fun_args->ping_status)) $post_data['ping_status'] = $fun_args->ping_status;

                                $updated_post_id = wp_update_post($post_data, true);

                                if (is_wp_error($updated_post_id))
                                {
                                    $results[] = "Error update $post_id: " . $updated_post_id->get_error_message();
                                    continue;
                                }

                                if (isset($fun_args->featured_image_id))
                                {
                                    $fid = intval($fun_args->featured_image_id);
                                    $fid > 0 ? set_post_thumbnail($post_id, $fid) : delete_post_thumbnail($post_id);
                                }

                                $results[] = "Updated $post_id";
                            }

                            // --- FEATURED IMAGE ---
                            elseif ($operation === 'set_featured_image')
                            {
                                $fid = intval($fun_args->featured_image_id ?? 0);
                                $image_url = isset($fun_args->image_url) ? trim($fun_args->image_url) : '';

                                if ($fid <= 0 && !empty($image_url))
                                {
                                    require_once ABSPATH . 'wp-admin/includes/media.php';
                                    require_once ABSPATH . 'wp-admin/includes/file.php';
                                    require_once ABSPATH . 'wp-admin/includes/image.php';

                                    $sideloaded = media_sideload_image($image_url, $post_id, null, 'id');

                                    if (is_wp_error($sideloaded))
                                    {
                                        $results[] = "Error featured $post_id: " . $sideloaded->get_error_message();
                                        continue;
                                    }

                                    $fid = (int)$sideloaded;
                                }

                                if ($fid <= 0)
                                {
                                    $results[] = "Error featured $post_id: missing image";
                                    continue;
                                }

                                $results[] = set_post_thumbnail($post_id, $fid)
                                    ? "Featured set $post_id ($fid)"
                                    : "Error featured $post_id";
                            }

                            elseif ($operation === 'delete_featured_image')
                            {
                                delete_post_thumbnail($post_id);
                                $results[] = "Removed featured $post_id";
                            }

                            // --- REST ---
                            elseif ($operation === 'trash')
                                $results[] = wp_trash_post($post_id) ? "Trashed $post_id" : "Error trash $post_id";

                            elseif ($operation === 'untrash')
                                $results[] = wp_untrash_post($post_id) ? "Restored $post_id" : "Error restore $post_id";

                            elseif ($operation === 'delete')
                                $results[] = wp_delete_post($post_id, true) ? "Deleted $post_id" : "Error delete $post_id";

                            elseif ($operation === 'duplicate')
                            {
                                $new_id = wp_insert_post(array(
                                    'post_title' => $existing_post->post_title . ' (Copy)',
                                    'post_content' => $existing_post->post_content,
                                    'post_excerpt' => $existing_post->post_excerpt,
                                    'post_status' => 'draft',
                                    'post_type' => $existing_post->post_type,
                                ), true);

                                $results[] = is_wp_error($new_id) ? "Error duplicate $post_id" : "Duplicated $post_id → $new_id";
                            }

                            elseif ($operation === 'append_content')
                            {
                                if (empty($fun_args->post_content)) { $results[] = "Error content $post_id"; continue; }
                                wp_update_post(['ID'=>$post_id,'post_content'=>$existing_post->post_content.$fun_args->post_content]);
                                $results[] = "Appended $post_id";
                            }

                            elseif ($operation === 'prepend_content')
                            {
                                if (empty($fun_args->post_content)) { $results[] = "Error content $post_id"; continue; }
                                wp_update_post(['ID'=>$post_id,'post_content'=>$fun_args->post_content.$existing_post->post_content]);
                                $results[] = "Prepended $post_id";
                            }

                            elseif ($operation === 'set_meta')
                            {
                                if (empty($fun_args->meta_key)) { $results[] = "Error meta_key $post_id"; continue; }
                                update_post_meta($post_id, sanitize_key($fun_args->meta_key), $fun_args->meta_value ?? '');
                                $results[] = "Meta set $post_id";
                            }

                            elseif ($operation === 'delete_meta')
                            {
                                if (empty($fun_args->meta_key)) { $results[] = "Error meta_key $post_id"; continue; }
                                delete_post_meta($post_id, sanitize_key($fun_args->meta_key));
                                $results[] = "Meta deleted $post_id";
                            }

                            elseif ($operation === 'set_terms')
                            {
                                $taxonomy = sanitize_key($fun_args->taxonomy ?? '');
                                $terms = array_map('intval', array_filter(array_map('trim', explode(',', $fun_args->terms ?? ''))));

                                if (!$taxonomy || empty($terms)) { $results[] = "Error terms $post_id"; continue; }

                                wp_set_object_terms($post_id, $terms, $taxonomy, false);
                                $results[] = "Terms set $post_id";
                            }
                        }

                        aiomatic_agent_add_tool_results($reply, array(
                            "tool_call_id" => $tool_call->id,
                            "role" => "tool",
                            "content" => implode("\n", $results),
                            'assistant_message' => $as_mes
                        ));
                    }
                    elseif ($tool_call->name === 'search_site_posts') 
                    {
                        if(isset($fun_args))
                        {
                            $query_str  = isset($fun_args->query) ? $fun_args->query : '';
                            $post_type  = (!empty($fun_args->post_type)) ? (array)$fun_args->post_type : array('post','page');
                            $post_status= (!empty($fun_args->post_status)) ? sanitize_text_field($fun_args->post_status) : 'any';
                            $limit      = (!empty($fun_args->posts_per_page)) ? min((int)$fun_args->posts_per_page, 20) : 5;
                            $offset     = (!empty($fun_args->offset)) ? max((int)$fun_args->offset, 0) : 0;

                            $args = array(
                                'post_type'      => $post_type,
                                'post_status'    => $post_status,
                                'posts_per_page' => $limit,
                                'offset'         => $offset,
                                'orderby'        => 'date',
                                'order'          => 'DESC',
                                'no_found_rows'  => true
                            );

                            // Keyword search
                            if (!empty($query_str)) 
                            {
                                $args['s'] = sanitize_text_field($query_str);
                                $args['orderby'] = 'relevance';
                            }

                            // Sorting
                            if (!empty($fun_args->orderby)) {
                                $args['orderby'] = sanitize_text_field($fun_args->orderby);
                            }
                            if (!empty($fun_args->order)) {
                                $args['order'] = strtoupper($fun_args->order) === 'ASC' ? 'ASC' : 'DESC';
                            }
                            if (!empty($fun_args->meta_key)) {
                                $args['meta_key'] = sanitize_text_field($fun_args->meta_key);
                            }

                            // Author filter
                            if (!empty($fun_args->author_id)) {
                                $args['author'] = (int)$fun_args->author_id;
                            }

                            // Date filter (FIXED)
                            if (!empty($fun_args->date_after) || !empty($fun_args->date_before)) 
                            {
                                $date_query = array();

                                if (!empty($fun_args->date_after)) {
                                    $date_query['after'] = sanitize_text_field($fun_args->date_after);
                                }
                                if (!empty($fun_args->date_before)) {
                                    $date_query['before'] = sanitize_text_field($fun_args->date_before);
                                }

                                $date_query['inclusive'] = true;
                                $args['date_query'] = array($date_query);
                            }

                            // Taxonomy filter
                            if (!empty($fun_args->taxonomy) && !empty($fun_args->terms)) 
                            {
                                $terms = array_map('intval', explode(',', $fun_args->terms));

                                $args['tax_query'] = array(
                                    array(
                                        'taxonomy' => sanitize_text_field($fun_args->taxonomy),
                                        'field'    => 'term_id',
                                        'terms'    => $terms
                                    )
                                );
                            }

                            // Meta filters
                            $meta_query = array('relation' => 'AND');

                            // FIXED featured image logic
                            if (isset($fun_args->has_featured_image)) 
                            {
                                if ($fun_args->has_featured_image === 'yes') {
                                    $meta_query[] = array(
                                        'key'     => '_thumbnail_id',
                                        'compare' => 'EXISTS'
                                    );
                                } elseif ($fun_args->has_featured_image === 'no') {
                                    $meta_query[] = array(
                                        'relation' => 'OR',
                                        array(
                                            'key'     => '_thumbnail_id',
                                            'compare' => 'NOT EXISTS'
                                        ),
                                        array(
                                            'key'     => '_thumbnail_id',
                                            'value'   => '',
                                            'compare' => '='
                                        )
                                    );
                                }
                            }

                            // Custom meta filters (max 5)
                            if (!empty($fun_args->meta_filters)) 
                            {
                                $allowed_compares = ['=', '!=', '>', '>=', '<', '<=', 'LIKE', 'EXISTS', 'NOT EXISTS'];
                                $count = 0;

                                // STRING FORMAT
                                if (is_string($fun_args->meta_filters)) 
                                {
                                    $filters = explode('|', $fun_args->meta_filters);

                                    foreach ($filters as $raw_filter) 
                                    {
                                        if ($count >= 5) break;

                                        $parts = array_map('trim', explode(':', trim($raw_filter)));

                                        $key     = $parts[0] ?? '';
                                        $value   = $parts[1] ?? '';
                                        $compare = strtoupper($parts[2] ?? '=');

                                        if (!in_array($compare, $allowed_compares, true)) {
                                            $compare = '=';
                                        }

                                        if ($key === '') continue;

                                        if ($compare === 'EXISTS' || $compare === 'NOT EXISTS') {
                                            $meta_query[] = array(
                                                'key'     => sanitize_text_field($key),
                                                'compare' => $compare
                                            );
                                        } else {
                                            $meta_query[] = array(
                                                'key'     => sanitize_text_field($key),
                                                'value'   => sanitize_text_field($value),
                                                'compare' => $compare
                                            );
                                        }

                                        $count++;
                                    }
                                }
                                // ARRAY FORMAT fallback
                                elseif (is_array($fun_args->meta_filters)) 
                                {
                                    foreach ($fun_args->meta_filters as $filter) 
                                    {
                                        if ($count >= 5) break;
                                        if (empty($filter->key)) continue;

                                        $compare = strtoupper($filter->compare ?? '=');
                                        if (!in_array($compare, $allowed_compares, true)) {
                                            $compare = '=';
                                        }

                                        if ($compare === 'EXISTS' || $compare === 'NOT EXISTS') {
                                            $meta_query[] = array(
                                                'key'     => sanitize_text_field($filter->key),
                                                'compare' => $compare
                                            );
                                        } else {
                                            $meta_query[] = array(
                                                'key'     => sanitize_text_field($filter->key),
                                                'value'   => sanitize_text_field($filter->value ?? ''),
                                                'compare' => $compare
                                            );
                                        }

                                        $count++;
                                    }
                                }
                            }

                            if (count($meta_query) > 1) {
                                $args['meta_query'] = $meta_query;
                            }
                            
                            $has_excerpt_filter = null;
                            $excerpt_filter_cb  = null;

                            if (isset($fun_args->has_excerpt)) {
                                if ($fun_args->has_excerpt === 'yes') {
                                    $has_excerpt_filter = 'yes';
                                } elseif ($fun_args->has_excerpt === 'no') {
                                    $has_excerpt_filter = 'no';
                                }
                            }

                            $length_filter_cb = null;

                            $min_len = isset($fun_args->min_content_length) ? (int)$fun_args->min_content_length : 0;
                            $max_len = isset($fun_args->max_content_length) && (int)$fun_args->max_content_length > 0
                                ? (int)$fun_args->max_content_length
                                : 0;

                            if ($has_excerpt_filter !== null) {

                                $excerpt_filter_cb = function ($where) use ($has_excerpt_filter) {
                                    global $wpdb;

                                    if ($has_excerpt_filter === 'yes') {
                                        $where .= " AND {$wpdb->posts}.post_excerpt != ''";
                                    } elseif ($has_excerpt_filter === 'no') {
                                        $where .= " AND ({$wpdb->posts}.post_excerpt = '' OR {$wpdb->posts}.post_excerpt IS NULL)";
                                    }

                                    return $where;
                                };

                                add_filter('posts_where', $excerpt_filter_cb);
                            }
                            if ($min_len > 0 || $max_len > 0) {

                                $length_filter_cb = function ($where) use ($min_len, $max_len) {
                                    global $wpdb;

                                    if ($min_len > 0) {
                                        $where .= $wpdb->prepare(
                                            " AND CHAR_LENGTH({$wpdb->posts}.post_content) >= %d",
                                            $min_len
                                        );
                                    }

                                    if ($max_len > 0) {
                                        $where .= $wpdb->prepare(
                                            " AND CHAR_LENGTH({$wpdb->posts}.post_content) <= %d",
                                            $max_len
                                        );
                                    }

                                    return $where;
                                };

                                add_filter('posts_where', $length_filter_cb);
                            }
                            $query = new WP_Query($args);
                            
                            if ($excerpt_filter_cb !== null) {
                                remove_filter('posts_where', $excerpt_filter_cb);
                            }
                            if ($length_filter_cb !== null) {
                                remove_filter('posts_where', $length_filter_cb);
                            }
                            $results = array();

                            if ($query->have_posts()) 
                            {
                                foreach ($query->posts as $post) 
                                {
                                    $content = wp_strip_all_tags($post->post_content);
                                    $results[] = sprintf(
                                        "ID: %d | Title: %s | Status: %s | Date: %s | Words: %d | Image: %s | Excerpt: %s",
                                        $post->ID,
                                        $post->post_title,
                                        $post->post_status,
                                        $post->post_date,
                                        str_word_count($content),
                                        has_post_thumbnail($post->ID) ? 'yes' : 'no',
                                        !empty($post->post_excerpt) ? 'yes' : 'no'
                                    );
                                }

                                wp_reset_postdata();
                            }

                            if (empty($results)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "No results found for the given filters.",
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            $output = "Filtered Search Results:\n\n" . implode("\n---\n", $results);

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => aiomatic_substr($output, 0, 30000),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'arguments not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'wp_sideload_media') 
                    {
                        if(isset($fun_args->image_url))
                        {
                            $image_url = $fun_args->image_url;
                            $post_id = 0;
                            if(isset($fun_args->post_id))
                            {
                                $post_id = $fun_args->post_id;
                            }

                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error: No image URL provided.',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            require_once(ABSPATH . 'wp-admin/includes/media.php');
                            require_once(ABSPATH . 'wp-admin/includes/file.php');
                            require_once(ABSPATH . 'wp-admin/includes/image.php');

                            $result = media_sideload_image($image_url, $post_id, "AIomatic", 'id');

                            if (is_wp_error($result)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result->get_error_message(),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => "Attachment ID: $result | URL: " . wp_get_attachment_url($result),
                                'assistant_message' => $as_mes
                            ));
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'get_wp_media_info') 
                    {
                        if(isset($fun_args->post_id) || isset($fun_args->attachment_id))
                        {
                            $post_id       = isset($fun_args->post_id) ? intval($fun_args->post_id) : 0;
                            $attachment_id = isset($fun_args->attachment_id) ? intval($fun_args->attachment_id) : 0;
                            $include_att   = isset($fun_args->include_attachments) ? (bool)$fun_args->include_attachments : false;

                            $output = array();

                            // =========================
                            // ATTACHMENT MODE
                            // =========================
                            if ($attachment_id > 0)
                            {
                                $attachment = get_post($attachment_id);

                                if (!$attachment || $attachment->post_type !== 'attachment')
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: Attachment not found.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $file_path = get_attached_file($attachment_id);
                                $file_url  = wp_get_attachment_url($attachment_id);
                                $metadata  = wp_get_attachment_metadata($attachment_id);

                                $output[] = "Attachment ID: $attachment_id";
                                $output[] = "URL: $file_url";
                                $output[] = "Mime: {$attachment->post_mime_type}";
                                $output[] = "File: $file_path";

                                if (!empty($metadata['width']) && !empty($metadata['height']))
                                {
                                    $output[] = "Dimensions: {$metadata['width']}x{$metadata['height']}";
                                }

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => implode("\n", $output),
                                    'assistant_message' => $as_mes
                                ));

                                continue;
                            }

                            // =========================
                            // POST MODE
                            // =========================
                            if ($post_id > 0)
                            {
                                $post = get_post($post_id);

                                if (!$post)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error: Post not found.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }

                                $output[] = "Post ID: $post_id";
                                $output[] = "Title: {$post->post_title}";

                                // Featured image
                                $thumb_id = get_post_thumbnail_id($post_id);

                                if ($thumb_id)
                                {
                                    $thumb_url = wp_get_attachment_url($thumb_id);
                                    $meta      = wp_get_attachment_metadata($thumb_id);

                                    $output[] = "Featured Image: YES";
                                    $output[] = "Featured Image ID: $thumb_id";
                                    $output[] = "Featured Image URL: $thumb_url";

                                    if (!empty($meta['width']) && !empty($meta['height']))
                                    {
                                        $output[] = "Featured Image Size: {$meta['width']}x{$meta['height']}";
                                    }
                                }
                                else
                                {
                                    $output[] = "Featured Image: NO";
                                }

                                // Attachments
                                if ($include_att)
                                {
                                    $attachments = get_children(array(
                                        'post_parent' => $post_id,
                                        'post_type'   => 'attachment',
                                        'numberposts' => 10
                                    ));

                                    if (!empty($attachments))
                                    {
                                        $output[] = "--- Attachments ---";

                                        foreach ($attachments as $att)
                                        {
                                            $att_id  = $att->ID;
                                            $att_url = wp_get_attachment_url($att_id);
                                            $meta    = wp_get_attachment_metadata($att_id);

                                            $line = "ID: $att_id | Type: {$att->post_mime_type} | URL: $att_url";

                                            if (!empty($meta['width']) && !empty($meta['height']))
                                            {
                                                $line .= " | {$meta['width']}x{$meta['height']}";
                                            }

                                            $output[] = $line;
                                        }
                                    }
                                    else
                                    {
                                        $output[] = "Attachments: none";
                                    }
                                }

                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => implode("\n", $output),
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'post_id or attachment_id parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'query_toubiz_events') 
                    {
                        if (!function_exists('is_plugin_active')) 
                        {
                            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                        }
                        $plugin_active = is_plugin_active('aiomatic-extension-toubiz-api/aiomatic-extension-toubiz-api.php');
                        if (!$plugin_active) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Required plugin (Aimogen Extension Toubiz API) not activated.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }
                        if (!function_exists('aiomatic_get_toubiz_api_results')) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Required plugin (Aimogen Extension Toubiz API) not correctly installed.',
                                'assistant_message' => $as_mes
                            ));
                            continue;
                        }
                        $search = '';
                        if(isset($fun_args->search))
                        {
                            $search = $fun_args->search;
                        }
                        $date_after = '';
                        if(isset($fun_args->date_after))
                        {
                            $date_after = $fun_args->date_after;
                        }
                        $date_before = '';
                        if(isset($fun_args->date_before))
                        {
                            $date_before = $fun_args->date_before;
                        }
                        $type = '';
                        if(isset($fun_args->type))
                        {
                            $type = $fun_args->type;
                        }
                        $event_type = '';
                        if(isset($fun_args->event_type))
                        {
                            $event_type = $fun_args->event_type;
                        }
                        $rectangle_area = '';
                        if(isset($fun_args->rectangle_area))
                        {
                            $rectangle_area = $fun_args->rectangle_area;
                        }
                        $distance_from = '';
                        if(isset($fun_args->distance_from))
                        {
                            $distance_from = $fun_args->distance_from;
                        }
                        $languages = '';
                        if(isset($fun_args->languages))
                        {
                            $languages = $fun_args->languages;
                        }
                        $toubiz_data = aiomatic_get_toubiz_api_results($search, $date_after, $date_before, $type, $event_type, $rectangle_area, $distance_from, $languages);
                        if ($toubiz_data === false) 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'Failed to access Toubiz API',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to access Toubiz API: ' . print_r($tool_call, true));
                        } 
                        else 
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => $toubiz_data,
                                'assistant_message' => $as_mes
                            ));
                        }
                    }
                    elseif ($tool_call->name === 'website_scraper') 
                    {
                        if(isset($fun_args->url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $scurl = $fun_args->url;
                            if (empty($scurl) || !filter_var($scurl, FILTER_VALIDATE_URL)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid scrape url provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $parsed = parse_url($scurl);
                            if (!isset($parsed['scheme']) || !in_array(strtolower($parsed['scheme']), ['http', 'https']))
                            {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Only http/https URLs are allowed',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            $host = $parsed['host'];
                            $ip = gethostbyname($host);
                            if (
                                $ip === '127.0.0.1' ||
                                str_starts_with($ip, '10.') ||
                                str_starts_with($ip, '192.168.') ||
                                preg_match('/^172\.(1[6-9]|2\d|3[0-1])\./', $ip)
                            ) {
                                aiomatic_agent_add_tool_results($reply, [
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Access to local/internal URLs is not allowed',
                                    'assistant_message' => $as_mes
                                ]);
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['scrape_method']) && trim($aiomatic_Chatbot_Settings['scrape_method']) != '')
                            {
                                $scrape_method = trim($aiomatic_Chatbot_Settings['scrape_method']);
                            }
                            else
                            {
                                $scrape_method = '0';
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_chars']) && trim($aiomatic_Chatbot_Settings['max_chars']) != '')
                            {
                                $max_chars = trim($aiomatic_Chatbot_Settings['max_chars']);
                            }
                            else
                            {
                                $max_chars = '';
                            }
                            $scrape_selector = 'auto';
                            $scrape_string = '';
                            if (isset($aiomatic_Chatbot_Settings['strip_tags']) && trim($aiomatic_Chatbot_Settings['strip_tags']) != '')
                            {
                                $strip_tags = trim($aiomatic_Chatbot_Settings['strip_tags']);
                            }
                            else
                            {
                                $strip_tags = '0';
                            }
                            $scraped_data = aiomatic_scrape_page($scurl, $scrape_method, $scrape_selector, $scrape_string);
                            if($scraped_data === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to scrape website URL: ' . $scurl,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                if($strip_tags == '1')
                                {
                                    $scraped_data = wp_strip_all_tags($scraped_data);
                                }
                                else
                                {
                                    $scraped_data = aiomatic_fix_relative_links($scraped_data, $scurl);
                                }
                                if(!empty($max_chars) && is_numeric($max_chars))
                                {
                                    $scraped_data = (aiomatic_strlen($scraped_data) > intval($max_chars)) ? aiomatic_substr($scraped_data, 0, intval($max_chars)) : $scraped_data;
                                }
                                $scraped_data = aiomatic_substr($scraped_data, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $scraped_data,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'rss_feed_parser') 
                    {
                        if(isset($fun_args->url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $scurl = $fun_args->url;
                            if (empty($scurl)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty RSS feed URL provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_rss_items']) && trim($aiomatic_Chatbot_Settings['max_rss_items']) != '')
                            {
                                $max_rss_items = intval(trim($aiomatic_Chatbot_Settings['max_rss_items']));
                            }
                            else
                            {
                                $max_rss_items = PHP_INT_MAX;
                            }
                            if (isset($aiomatic_Chatbot_Settings['rss_template']) && trim($aiomatic_Chatbot_Settings['rss_template']) != '')
                            {
                                $rss_template = trim($aiomatic_Chatbot_Settings['rss_template']);
                            }
                            else
                            {
                                $rss_template = '[%%item_counter%%]: %%item_title%% - %%item_description%%';
                            }
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to load RSS parser library',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($scurl);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error in parsing RSS feed: ' . $feed->error(),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $final_result = '';
                            $items = $feed->get_items();
                            foreach($items as $itemx)
                            {
                                $post_link = trim($itemx->get_permalink());
                                $post_fcats = $itemx->get_categories();
                                if ($fauthor = $itemx->get_author()) 
                                {
                                    $user_name = $fauthor->get_name();
                                }
                                else
                                {
                                    $user_name = '';
                                }
                                $feed_cats = array();
                                if(is_array($post_fcats))
                                {
                                    foreach($post_fcats as $cata)
                                    {
                                        $feed_cats[] = $cata->__toString();
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                }
                                else
                                {
                                    $post_cats = '';
                                }
                                $post_excerpt = $itemx->get_description();
                                $final_content = $itemx->get_content();
                                $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                            }
                            $template_copy = '';
                            $processed = 0;
                            foreach($rss_feeds as $rtitle => $this_rss)
                            {
                                if(!empty($max_rss_items) && $processed >= $max_rss_items)
                                {
                                    break;
                                }
                                $template_copy = $rss_template;
                                $template_copy = str_replace('%%item_counter%%', $processed + 1, $template_copy);
                                $template_copy = str_replace('%%item_title%%', $rtitle, $template_copy);
                                $template_copy = str_replace('%%item_content%%', $this_rss['content'], $template_copy);
                                $template_copy = str_replace('%%item_description%%', $this_rss['excerpt'], $template_copy);
                                $template_copy = str_replace('%%item_url%%', $this_rss['url'], $template_copy);
                                $template_copy = str_replace('%%item_author%%', $this_rss['author'], $template_copy);
                                $template_copy = str_replace('%%item_categories%%', $this_rss['cats'], $template_copy);
                                if(!empty($template_copy))
                                {
                                    $final_result .= $template_copy . PHP_EOL;
                                }
                                $processed++;
                            }
                            if(empty($final_result))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse RSS URL (no data returned): ' . $scurl,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_result,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'google_results_parser') 
                    {
                        if(isset($fun_args->keywords))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $keywords = $fun_args->keywords;
                            if (empty($keywords)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty keywords parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Chatbot_Settings['max_google_items']) && trim($aiomatic_Chatbot_Settings['max_google_items']) != '')
                            {
                                $max_google_items = intval(trim($aiomatic_Chatbot_Settings['max_google_items']));
                            }
                            else
                            {
                                $max_google_items = PHP_INT_MAX;
                            }
                            if (isset($aiomatic_Chatbot_Settings['google_template']) && trim($aiomatic_Chatbot_Settings['google_template']) != '')
                            {
                                $google_template = trim($aiomatic_Chatbot_Settings['google_template']);
                            }
                            else
                            {
                                $google_template = '[%%item_counter%%]: %%item_title%% - %%item_snippet%%';
                            }
                            $locale = '';
                            if (isset($aiomatic_Main_Settings['internet_gl']) && $aiomatic_Main_Settings['internet_gl'] != '')
                            {
                                $locale = $aiomatic_Main_Settings['internet_gl'];
                            }
                            $internet_rez = aiomatic_internet_result($keywords, true, $locale);
                            $processed = 0;
                            $final_res = '';
                            foreach($internet_rez as $emb)
                            {
                                if(!empty($max_google_items) && $processed >= $max_google_items)
                                {
                                    break;
                                }
                                $template_copy = $google_template;
                                $template_copy = str_replace('%%item_counter%%', $processed + 1, $template_copy);
                                $template_copy = str_replace('%%item_title%%', $emb['title'], $template_copy);
                                $template_copy = str_replace('%%item_snippet%%', $emb['snippet'], $template_copy);
                                $template_copy = str_replace('%%item_url%%', $emb['link'], $template_copy);
                                $final_res .= $template_copy . PHP_EOL;
                                $processed++;
                            }
                            if(empty($final_res))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse Google SERP for keyword (no data returned): ' . $keywords,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $final_res = aiomatic_substr($final_res, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $final_res,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'keywords parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'royalty_free_image_search') 
                    {
                        if(isset($fun_args->keyword))
                        {
                            $raw_img_list = array();
                            $full_result_list = array();
                            $result = '';
                            $keyword = $fun_args->keyword;
                            $keyword = function_exists('aiomatic_normalize_royalty_free_image_keyword')
                                ? aiomatic_normalize_royalty_free_image_keyword($keyword)
                                : sanitize_text_field(wp_strip_all_tags((string) $keyword));
                            if (empty($keyword)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty keyword parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $temp_img_attr = '';
                            $attached_id = '';
                            $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $keyword, $temp_img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                            if(empty($temp_get_img))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to get royalty free image for keyword: ' . $keyword,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $temp_get_img = aiomatic_sanitize_image_src($temp_get_img);
                                if($temp_get_img !== false)
                                {
                                    aiomatic_agent_add_tool_direct_message($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => '<img class="image_max_w_ai" src="' . $temp_get_img . '">',
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'keyword parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'query_wp_database') 
                    {
                        if(isset($fun_args->query))
                        {
                            $query = $fun_args->query;
                            if (empty($query)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty query parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            if (isset($aiomatic_Chatbot_Settings['database_command_types']) && is_array($aiomatic_Chatbot_Settings['database_command_types']) && !empty($aiomatic_Chatbot_Settings['database_command_types']))
                            {
                                $allowed_commands = $aiomatic_Chatbot_Settings['database_command_types'];
                            }
                            else
                            {
                                $allowed_commands = array('SELECT');
                            }
                            preg_match('/^\s*(\w+)/i', $query, $matches);
                            $query_type = strtoupper($matches[1] ?? '');
                            if (!in_array($query_type, $allowed_commands, true)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => "Query type '$query_type' is not allowed. Allowed types: " . implode(', ', $allowed_commands),
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            global $wpdb;
                            try 
                            {
                                $lead_result = null;
                                if ($query_type === 'SELECT') 
                                {
                                    $lead_result = $wpdb->get_results($query, ARRAY_A);
                                } 
                                elseif (in_array($query_type, array('INSERT', 'UPDATE', 'DELETE'), true)) 
                                {
                                    $lead_result = $wpdb->query($query); 
                                }
                                if ($lead_result === null || $lead_result === false) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Error! Invalid query or no results found.',
                                        'assistant_message' => $as_mes
                                    ));
                                } 
                                else 
                                {
                                    if ($query_type === 'SELECT' && count($lead_result) > 500) {
                                        $lead_result = array_slice($lead_result, 0, 500);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => json_encode($lead_result), 
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            } 
                            catch (Exception $e) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Error executing the query: ' . $e->getMessage(),
                                    'assistant_message' => $as_mes
                                ));
                            }
                            continue;
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'aimogen_execute_omniblock_rule') 
                    {
                        if(isset($fun_args->omniblock_id))
                        {
                            if(isset($fun_args->input_parameters))
                            {
                                $input_text = $fun_args->input_parameters;
                            }
                            else
                            {
                                $input_text = '';
                            }
                            $omniblock_id = $fun_args->omniblock_id;
                            if (empty($omniblock_id)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty omniblock_id parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            if (isset($aiomatic_Chatbot_Settings['god_omniblock_rules']) && !empty(trim($aiomatic_Chatbot_Settings['god_omniblock_rules'])))
                            {
                                $omniblock_descriptions = array();
                                $omni_arr = preg_split('/\r\n|\r|\n/', trim($aiomatic_Chatbot_Settings['god_omniblock_rules']));
                                $omni_arr = array_map('trim', $omni_arr);
                                $omni_arr = array_filter($omni_arr);
                                foreach ($omni_arr as $line) {
                                    if (strpos($line, '=>') !== false) {
                                        [$id, $desc] = array_map('trim', explode('=>', $line, 2));
                                        if (!empty($id) && !empty($desc)) {
                                            $omniblock_descriptions[$id] = "`$id`: $desc";
                                        }
                                    }
                                }
                                if(!array_key_exists($omniblock_id, $omniblock_descriptions))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'This OmniBlock ID does not exist in the configured rules',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            else
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No OmniBlock rules configured in settings',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $input_text = json_decode($input_text, true);
                            if($input_text === null || $input_text === false || $input_text === true)
                            {
                                $input_text = [];
                            }
                            require_once (dirname(__FILE__) . "/aiomatic-automation.php"); 
                            $cont = 0;
                            $id_parts = explode('_', $omniblock_id);
                            if(!isset($id_parts[1]))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Incorrect OmniBlock ID submitted in request',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if(count($id_parts) > 2)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Incorrect format for OmniBlock IDs',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $param = $id_parts[0];
                            $omniTriggerID = $id_parts[1];
                            $rules = get_option('aiomatic_omni_list', array());
                            $found = false;
                            if (!empty($rules)) 
                            {
                                $default_block_types = aimogen_execute_omniblock_rules_default_block_types(); 
                                foreach ($rules as $request => $bundle[]) 
                                {
                                    if ($cont == $param) 
                                    {
                                        $bundle_values    = array_values($bundle);
                                        $myValues         = $bundle_values[$cont];
                                        $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                                        $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                                        $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                                        $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                                        $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                                        $main_keywords    = isset($array_my_values[4]) ? $array_my_values[4] : '';
                                        $title_once       = isset($array_my_values[5]) ? $array_my_values[5] : '';
                                        $rule_description = isset($array_my_values[6]) ? $array_my_values[6] : '';
                                        $rule_unique_id   = isset($array_my_values[7]) ? $array_my_values[7] : '';
                                        $sortable_cards   = isset($array_my_values[8]) ? $array_my_values[8] : '';
                                        $more_keywords    = isset($array_my_values[9]) ? $array_my_values[9] : '';
                                        $days_no_run      = isset($array_my_values[10]) ? $array_my_values[10] : '';
                                        $block_data       = json_decode($sortable_cards, true);
                                        if(!empty($block_data))
                                        {
                                            foreach($block_data as $index => $current_block)
                                            {
                                                $card_type_found = array();
                                                foreach($default_block_types as $def_card)
                                                {
                                                    if($current_block['type'] == $def_card['id'])
                                                    {
                                                        $card_type_found = $def_card;
                                                        break;
                                                    }
                                                }
                                                if(!empty($card_type_found) && $omniTriggerID == $current_block['identifier'] && $current_block['type'] === 'ai_chatbot_omniblock')
                                                {
                                                    $return_last_result = true;
                                                    $return_me = aiomatic_run_rule($cont, 5, 1, 0, null, '', $omniTriggerID, $return_last_result, $input_text);
                                                    if($return_me == 'fail')
                                                    {
                                                        aiomatic_log_to_file('OmniBlock AI Chatbot Trigger rule running failed, rule ID: ' . $param . ' OmniBlock ID: ' . $omniTriggerID);
                                                    }
                                                    aiomatic_agent_add_tool_results($reply, array(
                                                        "tool_call_id" => $tool_call->id,
                                                        "role" => "tool",
                                                        "content" => wp_kses_post($return_me), 
                                                        'assistant_message' => $as_mes
                                                    ));
                                                    $found = true;
                                                    break 2;
                                                }
                                            }
                                        }
                                    }
                                    $cont = $cont + 1;
                                }
                                if($found == false)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Specified \'AI Chatbot Trigger\' OmniBlock ID not found(4): ' . $omniblock_id,
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            } 
                            else 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'No rules found for aiomatic_omni_list!',
                                    'assistant_message' => $as_mes
                                ));
                            }
                            continue;
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'query parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                            continue;
                        }
                    }
                    elseif ($tool_call->name === 'generate_ai_model_reasoning') 
                    {
                        if(isset($fun_args->prompt))
                        {
                            $prompt = $fun_args->prompt;
                            if (empty($prompt)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty prompt parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $model = '';
                            if(isset($fun_args->model))
                            {
                                $model = $fun_args->model;
                            }
                            if (empty($model)) 
                            {
                                $model = AIMOGEN_DEFAULT_MODEL;
                            }
                            if (!isset($aiomatic_Main_Settings['app_id'])) 
                            {
                                $aiomatic_Main_Settings['app_id'] = '';
                            }
                            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
                            $appids = array_filter($appids);
                            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
                            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
                            if (empty($token))
                            {
                                aiomatic_log_to_file('You need to enter an OpenAI API key for this to work!');
                                $result = '[ERROR] API key not configured in plugin settings.';
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $result,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $query_token_count = count(aiomatic_encode($prompt));
                            $max_tokens = aimogenpro_get_max_tokens($model);
                            $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($prompt);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $prompt = aiomatic_substr($prompt, 0, $string_len);
                                $prompt = trim($prompt);
                                $query_token_count = count(aiomatic_encode($prompt));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $thread_id = '';
                            $aierror = '';
                            $finish_reason = '';
                            remove_filter('aiomatic_ai_reply_raw', 'aiomatic_agent_handle_god_mode_response');
                            $generated_text = aiomatic_generate_text($token, $model, $prompt, $available_tokens, 1, 1, 0, 0, false, 'aiThinking', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', '', $thread_id, '', 'disabled', '', false, false, array(), '', '', '');
                            add_filter('aiomatic_ai_reply_raw', 'aiomatic_agent_handle_god_mode_response', 10, 2);
                            if($generated_text === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => '[ERROR] Failed to generate content using AI writer: ' . $model . ' - error: ' . $aierror,
                                    'assistant_message' => $as_mes
                                ));
                            }
                            else
                            {
                                $new_post_content = aiomatic_sanitize_ai_result($generated_text);
                                if(empty($new_post_content))
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => '[ERROR] No content returned by the AI writer!',
                                        'assistant_message' => $as_mes
                                    ));
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => $new_post_content,
                                        'assistant_message' => $as_mes
                                    ));
                                }
                            }
                            continue;
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'prompt parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'youtube_video_captions') 
                    {
                        if(isset($fun_args->url))
                        {
                            $result = '';
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $zurl = $fun_args->url;
                            if (empty($zurl)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $returned_caption = '';
                            $video_id = '';
                            preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $zurl, $amatches);
                            if(isset($amatches[1]))
                            {
                                $video_id = $amatches[1];
                            }
                            $caprez = false;
                            if(!empty($video_id))
                            {
                                try
                                {
                                    $caprez = aiomatic_get_video_transcript($video_id);
                                }
                                catch(Exception $e)
                                {
                                    try 
                                    {
                                        $caprez = aiomatic_get_video_transcript_2($video_id);
                                    } 
                                    catch (Exception $e) 
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to get transcript for video ID ' . $video_id . ': ' . $e->getMessage());
                                        }
                                    }
                                }
                            }
                            if(is_array($caprez) && isset($caprez['text']))
                            {
                                $returned_caption = $caprez['text'];
                            }
                            if(empty($returned_caption))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse YouTube Video captions from URL (no data returned): ' . $zurl,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                $returned_caption = aiomatic_substr($returned_caption, 0, 400000);
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $returned_caption,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'youtube_video_search') 
                    {
                        if(isset($fun_args->keyword))
                        {
                            $result = '';
                            $keyword = $fun_args->keyword;
                            if (empty($keyword)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty keyword parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $new_vid = aiomatic_get_video($keyword, '', array());
                            if(empty($new_vid))
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to parse YouTube video search results for keyword (no data returned): ' . $keyword,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else
                            {
                                aiomatic_agent_add_tool_direct_message($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => $new_vid,
                                    'assistant_message' => $as_mes
                                ));
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'keyword parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'wp_send_email') 
                    {
                        if(isset($fun_args->subject) && isset($fun_args->content) && isset($fun_args->recipient_email))
                        {
                            $result = '';
                            $subject = $fun_args->subject;
                            $content = $fun_args->content;
                            $recipient_email = $fun_args->recipient_email;
                            if (empty($subject) || empty($content) || empty($recipient_email)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty subject, content or recipient_email parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                $admin_mail = get_bloginfo('admin_email');
                                $headers[] = 'From: Aimogen Plugin Chatbot <' . $admin_mail . '>';
                                $headers[] = 'Reply-To: ' . $admin_mail;
                                $headers[] = 'X-Mailer: PHP/' . phpversion();
                                $headers[] = 'Content-Type: text/html';
                                $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                $sent = wp_mail($recipient_email, $subject, $content, $headers);
                                if($sent === false)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to send email to address: ' . $recipient_email,
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'OK',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'subject, content or recipient_email parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'call_webhook') 
                    {
                        if(isset($fun_args->webhook_url) && isset($fun_args->method_selector))
                        {
                            $webhook_url = $fun_args->webhook_url;
                            if (empty($webhook_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty webhook_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $webhook_method = $fun_args->method_selector;
                            if (empty($webhook_method)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty method_selector parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content_type = '';
                            if(isset($fun_args->content_type))
                            {
                                $content_type = $fun_args->content_type;
                            }
                            $post_template = '';
                            if(isset($fun_args->data))
                            {
                                $post_template = $fun_args->data;
                            }
                            $headers_template = '';
                            if(isset($fun_args->headers))
                            {
                                $headers_template = $fun_args->headers;
                            }
                            $urlParsed = wp_parse_url( $webhook_url, PHP_URL_HOST );
                            if ( filter_var( $webhook_url, FILTER_VALIDATE_URL ) === FALSE || empty( $urlParsed ) )
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Invalid webhook_url entered ' . $webhook_url,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            else if ( $content_type == 'JSON' && empty( json_decode( $post_template, TRUE ) ) )
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'The JSON data must be valid ' . $webhook_url,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $headers = [];
                            if(!empty($headers_template))
                            {
                                $headers_template_arr = preg_split('/\r\n|\r|\n/', trim($headers_template));
                                foreach($headers_template_arr as $arr_fr)
                                {
                                    if(!empty(trim($arr_fr)) && strstr($arr_fr, '=>'))
                                    {
                                        $small_arr = explode('=>', $arr_fr);
                                        $headers[] = trim($small_arr[0]) . ':' . trim($small_arr[1]);
                                    }
                                }
                            }
                            $content_params = [];
                            if(!empty($post_template))
                            {
                                $post_template_arr = preg_split('/\r\n|\r|\n/', trim($post_template));
                                foreach($post_template_arr as $arr_fr)
                                {
                                    if(!empty(trim($arr_fr)) && strstr($arr_fr, '=>'))
                                    {
                                        $small_arr = explode('=>', $arr_fr);
                                        $content_params[trim($small_arr[0])] = trim($small_arr[1]);
                                    }
                                }
                            }
                            $ch = curl_init();
                            if ($ch === false) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to init curl in webhook execution',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                                $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                $randomness = array_rand($prx);
                                curl_setopt( $ch, CURLOPT_PROXY, trim($prx[$randomness]));
                                if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                {
                                    $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                    if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                    {
                                        curl_setopt( $ch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                    }
                                }
                            }
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            if ($webhook_method == 'POST' || $webhook_method == 'PUT' || $webhook_method == 'DELETE') 
                            {
                                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook_method);
                                if (!empty($content_params) && $content_type == 'form_data') {
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content_params));
                                } elseif (!empty($post_template) && $content_type == 'JSON') {
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_template));
                                    $headers[] = 'Content-Type: application/json';
                                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                                }
                            }
                            else
                            {
                                $query_string = http_build_query($content_params);
                                $webhook_url = $webhook_url . (strpos($webhook_url, '?') === false ? '?' : '&') . $query_string;
                            }
                            curl_setopt($ch, CURLOPT_URL, $webhook_url);

                            $response = curl_exec($ch);
                            if($response === false)
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Failed to send webhook request to ' . $webhook_url,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $err = curl_error($ch);
                            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);
                            if ($err) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Webhook request error to URL ' . $webhook_url . ' - error: ' . $err,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }

                            if ($statusCode >= 200 && $statusCode <= 299) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Webhook URL called successfully!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            } 
                            else 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Webhook unexpected return code to URL ' . $webhook_url . ' - return code: ' . $statusCode,
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'webhook_url or method_selector parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_facebook_post') 
                    {
                        if(isset($fun_args->content))
                        {
                            $result = '';
                            $zcontent = $fun_args->content;
                            if (empty($zcontent)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $fbomatic_active = false;
                                if (is_plugin_active('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php')) 
                                {
                                    $fbomatic_active = true;
                                }
                                if(!$fbomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (F-omatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $furl = '';
                                if(isset($fun_args->url))
                                {
                                    $furl = $fun_args->url;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['facebook_post_select']) && $aiomatic_Chatbot_Settings['facebook_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['facebook_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No page where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php' => array('F-omatic Automatic Post Generator', 'https://1.envato.market/fbomatic')));
                                $return_me = aiomatic_post_to_facebook($card_type_found, $zcontent, $furl, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Facebook posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Facebook posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Facebook posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Facebook posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Facebook posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_facebook_image') 
                    {
                        if(isset($fun_args->image_url))
                        {
                            $result = '';
                            $image_url = $fun_args->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $fbomatic_active = false;
                                if (is_plugin_active('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php')) 
                                {
                                    $fbomatic_active = true;
                                }
                                if(!$fbomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (F-omatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $caption = '';
                                if(isset($fun_args->caption))
                                {
                                    $caption = $fun_args->caption;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['facebook_post_select']) && $aiomatic_Chatbot_Settings['facebook_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['facebook_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No page where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php' => array('F-omatic Automatic Post Generator', 'https://1.envato.market/fbomatic')));
                                $return_me = aiomatic_post_image_to_facebook($card_type_found, $caption, $image_url, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Facebook image posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook image posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Facebook image posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Facebook image posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Facebook image posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Facebook image posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Facebook image posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_twitter_x_post') 
                    {
                        if(isset($fun_args->content))
                        {
                            $result = '';
                            $zcontent = $fun_args->content;
                            if (empty($zcontent)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $twitomatic_active = false;
                                if (is_plugin_active('twitomatic-twitter-post-generator/twitomatic-twitter-post-generator.php')) 
                                {
                                    $twitomatic_active = true;
                                }
                                if(!$twitomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Twitomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $image_url = '';
                                if(isset($fun_args->image_url))
                                {
                                    $image_url = $fun_args->image_url;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('twitomatic-twitter-post-generator/twitomatic-twitter-post-generator.php' => array('Twitomatic Automatic Post Generator', 'https://1.envato.market/twitomatic')));
                                $return_me = aiomatic_post_to_twitter($card_type_found, $zcontent, $image_url);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Twitter posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Twitter posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Twitter posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Twitter posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Twitter posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Twitter posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Twitter posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_threads_post') 
                    {
                        if(isset($fun_args->content))
                        {
                            $result = '';
                            $zcontent = $fun_args->content;
                            if (empty($zcontent)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $threadsomatic_active = false;
                                if (is_plugin_active('threadsomatic-threads-auto-poster/threadsomatic-threads-auto-poster.php')) 
                                {
                                    $threadsomatic_active = true;
                                }
                                if(!$threadsomatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Threadsomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $image_url = '';
                                if(isset($fun_args->image_url))
                                {
                                    $image_url = $fun_args->image_url;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('threadsomatic-threads-auto-poster/threadsomatic-threads-auto-poster.php' => array('Threadsomatic Threads Auto Poster', 'https://wpbay.com/product/threadsomatic-threads-auto-poster/')));
                                $return_me = aiomatic_post_to_threads($card_type_found, $zcontent, $image_url);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Threads posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Threads posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Threads posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Threads posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Threads posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Threads posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Threads posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_instagram_post') 
                    {
                        if(isset($fun_args->image_url))
                        {
                            $result = '';
                            $image_url = $fun_args->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('instamatic-instagram-post-generator/instamatic-instagram-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Instamatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $content = '';
                                if(isset($fun_args->content))
                                {
                                    $content = $fun_args->content;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('instamatic-instagram-post-generator/instamatic-instagram-post-generator.php' => array('iMediamatic Automatic Post Generator', 'https://1.envato.market/instamatic')));
                                $return_me = aiomatic_post_image_to_instagram($card_type_found, $content, $image_url);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Instagram posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Instagram posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Instagram posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Instagram posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Instagram posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Instagram posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Instagram posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_pinterest_post') 
                    {
                        if(isset($fun_args->image_url))
                        {
                            $result = '';
                            $image_url = $fun_args->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('pinterestomatic-pinterest-post-generator/pinterestomatic-pinterest-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Pinterestomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['pinterest_post_select']) && $aiomatic_Chatbot_Settings['pinterest_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['pinterest_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No boards where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $title = '';
                                if(isset($fun_args->title))
                                {
                                    $title = $fun_args->title;
                                }
                                $description = '';
                                if(isset($fun_args->description))
                                {
                                    $description = $fun_args->description;
                                }
                                $pin_url = '';
                                if(isset($fun_args->pin_url))
                                {
                                    $pin_url = $fun_args->pin_url;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('pinterestomatic-pinterest-post-generator/pinterestomatic-pinterest-post-generator.php' => array('Pinterestomatic Automatic Post Generator', 'https://1.envato.market/pinterestomatic')));
                                $return_me = aiomatic_post_image_to_pinterest($card_type_found, $description, $title, $pin_url, $image_url, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Pinterest posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Pinterest posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Pinterest posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Pinterest posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Pinterest posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Pinterest posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Pinterest posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_google_my_business_post') 
                    {
                        if(isset($fun_args->content) && isset($fun_args->image_url))
                        {
                            $result = '';
                            $image_url = $fun_args->image_url;
                            if (empty($image_url)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty image_url parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content = $fun_args->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('businessomatic-google-my-business-post-generator/businessomatic-google-my-business-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Businessomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $page_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['business_post_select']) && $aiomatic_Chatbot_Settings['business_post_select'] != '') {
                                    $page_to_post = $aiomatic_Chatbot_Settings['business_post_select'];
                                }
                                if (empty($page_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No pages where to publish the post was selected',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('businessomatic-google-my-business-post-generator/businessomatic-google-my-business-post-generator.php' => array('Businessomatic Automatic Post Generator', 'https://1.envato.market/businessomatic')));
                                $return_me = aiomatic_post_to_gmb($card_type_found, $content, $image_url, $page_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('GMB posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'GMB posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse GMB posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse GMB posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'GMB posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('GMB posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'GMB posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'image_url or content parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_youtube_community_post') 
                    {
                        if(isset($fun_args->content) && isset($fun_args->post_type))
                        {
                            $result = '';
                            $post_type = $fun_args->post_type;
                            if (empty($post_type)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty post_type parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $post_type = trim($post_type);
                            if($post_type != 'image' && $post_type != 'text')
                            {
                                $post_type = 'text';
                            }
                            $content = $fun_args->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $image_url = '';
                            if(isset($fun_args->image_url))
                            {
                                $image_url = $fun_args->image_url;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('youtubomatic-youtube-post-generator/youtubomatic-youtube-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Youtubomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                if($image_url != '')
                                {
                                    $media = array($image_url);
                                }
                                else
                                {
                                    $media = array();
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('youtubomatic-youtube-post-generator/youtubomatic-youtube-post-generator.php' => array('Youtubomatic Automatic Post Generator', 'https://1.envato.market/youtubomatic')));
                                $return_me = aiomatic_post_to_youtube_community($card_type_found, $content, $post_type, $media);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('YouTube Community posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'YouTube Community posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse YouTube Community posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse YouTube Community posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'YouTube Community posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('YouTube Community posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'YouTube Community posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content or post_type parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_reddit_post') 
                    {
                        if(isset($fun_args->content) && isset($fun_args->title))
                        {
                            $result = '';
                            $title = $fun_args->title;
                            if (empty($title)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty title parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content = $fun_args->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('redditomatic-reddit-post-generator/redditomatic-reddit-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Redditomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $subreddit_to_post = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['subreddits_list']) && $aiomatic_Chatbot_Settings['subreddits_list'] != '') {
                                    $subreddit_to_post = $aiomatic_Chatbot_Settings['subreddits_list'];
                                }
                                if (empty($subreddit_to_post)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No subreddits were defined where to publish the post',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('redditomatic-reddit-post-generator/redditomatic-reddit-post-generator.php' => array('Redditomatic Automatic Post Generator', 'https://1.envato.market/redditomatic')));
                                $return_me = aiomatic_post_to_reddit($card_type_found, $title, $content, 'auto', $subreddit_to_post);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Reddit posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Reddit posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse Reddit posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse Reddit posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Reddit posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Reddit posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Reddit posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content or title parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                    elseif ($tool_call->name === 'publish_linkedin_post') 
                    {
                        if(isset($fun_args->content) && isset($fun_args->title))
                        {
                            $result = '';
                            $title = $fun_args->title;
                            if (empty($title)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty title parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $content = $fun_args->content;
                            if (empty($content)) 
                            {
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'Empty content parameter provided',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                            $description = '';
                            $post_link = '';
                            $image_url = '';
                            if(isset($fun_args->description))
                            {
                                $description = $fun_args->description;
                            }
                            if(isset($fun_args->link))
                            {
                                $post_link = $fun_args->link;
                            }
                            if(isset($fun_args->image_url))
                            {
                                $image_url = $fun_args->image_url;
                            }
                            try 
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                $instamatic_active = false;
                                if (is_plugin_active('linkedinomatic-linkedin-post-generator/linkedinomatic-linkedin-post-generator.php')) 
                                {
                                    $instamatic_active = true;
                                }
                                if(!$instamatic_active)
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Required plugin (Linkedinomatic) not activated.',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                $selected_pages = '';
                                $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                                if (isset($aiomatic_Chatbot_Settings['linkedin_selected_pages']) && $aiomatic_Chatbot_Settings['linkedin_selected_pages'] != '') {
                                    $selected_pages = $aiomatic_Chatbot_Settings['linkedin_selected_pages'];
                                }
                                if (empty($selected_pages)) 
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'No pages selected where to post to LinkedIn',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                                $card_type_found = array('required_plugin' => array('linkedinomatic-linkedin-post-generator/linkedinomatic-linkedin-post-generator.php' => array('Linkedinomatic Automatic Post Generator', 'https://1.envato.market/linkedinomatic')));
                                $return_me = aiomatic_post_to_linkedin($card_type_found, $content, $image_url, $title, $post_link, $description, '1', $selected_pages);
                                if(isset($return_me['error']))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('LinkedIn posting failed: ' . $return_me['error']);
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'LinkedIn posting failed: ' . $return_me['error'],
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                elseif(empty($return_me))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Failed to parse LinkedIn posting results');
                                    }
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'Failed to parse LinkedIn posting results',
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                                else
                                {
                                    aiomatic_agent_add_tool_results($reply, array(
                                        "tool_call_id" => $tool_call->id,
                                        "role" => "tool",
                                        "content" => 'LinkedIn posting success: ' . json_encode($return_me, true),
                                        'assistant_message' => $as_mes
                                    ));
                                    continue;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('LinkedIn posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                }
                                aiomatic_agent_add_tool_results($reply, array(
                                    "tool_call_id" => $tool_call->id,
                                    "role" => "tool",
                                    "content" => 'LinkedIn posting failed: Exception thrown ' . esc_html($e->getMessage()) . '!',
                                    'assistant_message' => $as_mes
                                ));
                                continue;
                            }
                        }
                        else
                        {
                            aiomatic_agent_add_tool_results($reply, array(
                                "tool_call_id" => $tool_call->id,
                                "role" => "tool",
                                "content" => 'content or title parameter not found',
                                'assistant_message' => $as_mes
                            ));
                            aiomatic_log_to_file('Failed to decode function calling: ' . print_r($tool_call, true));
                        }
                    }
                }
            }
        }
    }
    return $reply;
    };
    add_filter('aiomatic_google_tools_ai_reply_raw', $agent_god_mode_callback, 10, 2);
    add_filter('aiomatic_ai_reply_raw', $agent_god_mode_callback, 10, 2);

    add_filter('aiomatic_ai_responses_reply_raw', $agent_responses_god_mode_callback, 10, 2);
}
?>
