<?php
defined('ABSPATH') or die();
function aiomatic_call_required_tool($requiredAction) 
{
    $toolOutputs = [];
    if (isset($requiredAction['submit_tool_outputs']) && isset($requiredAction['submit_tool_outputs']['tool_calls'])) 
    {
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        require_once(__DIR__ . '/res/amazon-direct.php');
        foreach($requiredAction['submit_tool_outputs']['tool_calls'] as $tc)
        {
            if($tc['type'] === 'function')
            {
                if (!isset($tc['function']))
                {
                    continue;
                }
                if (isset($tc['function']['arguments'])) 
                {
                    $result = '';
                    if (isset($tc['function']['arguments']) && is_string($tc['function']['arguments'])) 
                    {
                        $targs = json_decode($tc['function']['arguments'], true);
                        if($targs !== null)
                        {
                            $tc['function']['arguments'] = $targs;
                        }
                        else
                        {
                            $strips = stripslashes($tc['function']['arguments']);
                            $targs = json_decode($strips, true);
                            if($targs !== null)
                            {
                                $tc['function']['arguments'] = $targs;
                            }
                            else
                            {
                                $jsons = aiomatic_parse_multiple_json($tc['function']['arguments']);
                                if(!empty($jsons) && isset($jsons[0]))
                                {
                                    $tc['function']['arguments'] = $jsons[0];
                                }
                            }
                        }
                    }
                }
                if (!aiomatic_is_restricted_function_allowed($tc['function']['name'])) {
                    aiomatic_log_to_file('Blocked tool (central filter): ' . $tc['function']['name']);
                    $toolOutputs[] = [
                        'tool_call_id' => $tc['id'], 
                        'output' => 'You are not allowed to call this function (not admin)'
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                    continue;
                }
                if ($tc['function']['name'] === 'aimogen_wp_god_mode')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['called_function_name']))
                        {
                            $function_name = $tc['function']['arguments']['called_function_name'];
                            $params = $tc['function']['arguments']['parameter_array'];
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            if (isset($aiomatic_Chatbot_Settings['god_whitelisted_functions']) && trim($aiomatic_Chatbot_Settings['god_whitelisted_functions']) != '')
                            {
                                $white = trim($aiomatic_Chatbot_Settings['god_whitelisted_functions']);
                                $white = preg_split('/\r\n|\r|\n/', trim($white));
                                $white = array_filter($white);
                                if(!in_array($function_name, $white))
                                {
                                    if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                    {
                                        aiomatic_log_to_file('Function call not allowed (assistant), not whitelisted: ' . $function_name);
                                    }
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'You are not allowed to call this function (not on the whitelisted functions list)'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                            }
                            if (aiomatic_is_god_mode_function_blacklisted($function_name, $aiomatic_Chatbot_Settings))
                            {
                                if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                {
                                    aiomatic_log_to_file('Function call not allowed (assistant), blacklisted: ' . $function_name);
                                }
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'You are not allowed to call this function (on the blacklisted functions list)'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(function_exists($function_name))
                            {
                                if(!is_array($params))
                                {
                                    $jsony = json_decode($params, true);
                                    if($jsony !== null && is_array($jsony))
                                    {
                                        $params = $jsony;
                                    }
                                    else
                                    {
                                        if(empty($params))
                                        {
                                            $params = array();
                                        }
                                        else
                                        {
                                            $params = array($params);
                                        }
                                    }
                                }
                                if(isset($params['post_title']) && $function_name == 'wp_insert_post')
                                {
                                    $params = array($params);
                                }
                                $paramsAsString = aiomatic_format_function_params($params);
                                try {
                                    $reflection = new ReflectionFunction($function_name);
                                    $requiredParamsCount = $reflection->getNumberOfRequiredParameters();
                                    if(is_numeric($requiredParamsCount) && $requiredParamsCount > 0 && count($params) < $requiredParamsCount)
                                    {
                                        $result = $function_name . ' function has ' . $requiredParamsCount .' required parameters, but only ' . count($params) . ' were passed to it.';
                                    }
                                    else
                                    {
                                        if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                                        {
                                            aiomatic_log_to_file('Calling function (assistant) ' . $function_name . '(' . $paramsAsString . ')...');
                                        }
                                        $result = call_user_func_array($function_name, $params);
                                    }
                                } catch (Throwable $e) {
                                    $result = 'Invalid function: ' . $function_name;
                                }
                            }
                            else
                            {
                                $result = $function_name . ' function was not found on the system.';
                            }
                            if(isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on')
                            {
                                $paramsAsString = aiomatic_format_function_params($params);
                                if($result === false)
                                {
                                    aiomatic_log_to_file('Function (assistant) ' . $function_name . '(' . $paramsAsString . ') - returned false');
                                    $result = $function_name . ' returned false';
                                }
                                elseif(empty($result))
                                {
                                    aiomatic_log_to_file('Function (assistant)' . $function_name . '(' . $paramsAsString . ') - returned an empty response: ' . print_r($result, true));
                                    $result = $function_name . ' returned an empty response';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Function (assistant) ' . $function_name . '(' . $paramsAsString . ') - result: ' . print_r($result, true));
                                }
                            }
                            if(is_string($result))
                            {
                                $result = aiomatic_substr($result, 0, 400000);
                            }
                            if(is_object($result) || is_array($result))
                            {
                                $result = json_encode($result);
                                if ($result === false) {
                                    $result = 'Failed to encode tool result.';
                                }
                            }
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => (string) $result
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'called_function_name parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'end_chatbot_conversation')
                {
                    $toolOutputs[] = [
                        'tool_call_id' => $tc['id'], 
                        'echo' => 'AiomaticConversationEnded~!@#$%^&*()',
                        'output' => 'Conversation ended'
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                }
                elseif ($tc['function']['name'] === 'generate_chart')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['shortcode']))
                        {
                            $shortcode = $tc['function']['arguments']['shortcode'];
                            $result = do_shortcode($shortcode);
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'echo' => $result,
                                'output' => $result
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'shortcode parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_openai')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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']) != '')
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']),
                                        'output' => trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed'])
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                else
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => 'Image creation failed, please try again later.',
                                        'output' => 'Image creation failed, please try again later.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                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';
                            }
                            $aierror = '';
                            $result = aiomatic_generate_ai_image($token, 1, $prompt, $image_size, 'chatFunctionDalleImage', false, 0, $aierror, $model, $prompt);
                            if($result !== false && is_array($result))
                            {
                                foreach($result as $tmpimg)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($tmpimg) . '">',
                                        'output' => $tmpimg
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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']) != '')
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed']),
                                        'output' => trim($aiomatic_Chatbot_Settings['god_mode_dalle_failed'])
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                else
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => 'Image creation failed, please try again later.',
                                        'output' => 'Image creation failed, please try again later.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_stable_diffusion')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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';
                            }
                            $height = '512';
                            $width = '512';
                            if($image_size == '1024x1024')
                            {
                                $height = '1024';
                                $width = '1024';
                            }
                            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]))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult[1]) . '">',
                                    'output' => $airesult[1]
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Stable Diffusion image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_stable_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_stable_failed']) != '')
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => trim($aiomatic_Chatbot_Settings['god_mode_stable_failed']),
                                        'output' => trim($aiomatic_Chatbot_Settings['god_mode_stable_failed'])
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                else
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => 'Image creation failed, please try again later.',
                                        'output' => 'Image creation failed, please try again later.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_google')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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]))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult[1]) . '">',
                                    'output' => $airesult[1]
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Stable Diffusion image in AI chatbot: ' . $aierror);
                                if (isset($aiomatic_Chatbot_Settings['god_mode_stable_failed']) && trim($aiomatic_Chatbot_Settings['god_mode_stable_failed']) != '')
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => trim($aiomatic_Chatbot_Settings['god_mode_stable_failed']),
                                        'output' => trim($aiomatic_Chatbot_Settings['god_mode_stable_failed'])
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                else
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'echo' => 'Image creation failed, please try again later.',
                                        'output' => 'Image creation failed, please try again later.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_midjourney')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_ai_image_midjourney($prompt, $width, $height, 'chatFunctionMidjourneyImage', false, $aierror);
                            if($result !== false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Midjourney image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_replicate')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_replicate_image($prompt, $width, $height, 'chatFunctionReplicateImage', false, $aierror);
                            if($result !== false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Replicate image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_ideogram')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_ideogram_image($prompt, $width, $height, 'chatFunctionIdeogramImage', false, $aierror);
                            if($result !== false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Ideogram image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_image_cloudflare')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_cloudflare_image($prompt, $width, $height, 'chatFunctionCloudflareImage', false, $aierror);
                            if($result !== false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Cloudflare image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'manage_booking_calendar_booking') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $args = $tc['function']['arguments'];
                        if (empty($args['start_date']) || empty($args['end_date']) || empty($args['name']) || empty($args['email'])) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'Missing required booking parameters (start_date, end_date, name, email).'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $start_date  = sanitize_text_field($args['start_date']);
                        $end_date    = sanitize_text_field($args['end_date']);
                        $start_ts = strtotime($start_date);
                        $end_ts   = strtotime($end_date);
                        if (!$start_ts || !$end_ts || $end_ts < $start_ts) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'A valid date range is required.'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $name        = sanitize_text_field($args['name']);
                        $email       = sanitize_email($args['email']);
                        if (!is_email($email)) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'A valid email is required.'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $secondname  = isset($args['secondname']) ? sanitize_text_field($args['secondname']) : '';
                        $resource_id = isset($args['resource_id']) ? intval($args['resource_id']) : 1;

                        if (!function_exists('wpbc_api_is_dates_booked') || !function_exists('wpbc_api_booking_add_new')) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'Booking Calendar API functions are not available.'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'These dates are already booked, select different dates'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'Booking created: ' . $booking_id
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } else {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'Failed to create booking.'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'],
                            'output'       => 'Arguments not set for the booking function call.'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'create_stable_diffusion_video')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['image_url']))
                        {
                            $image_url = $tc['function']['arguments']['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty image_url query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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]))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<div style="padding-bottom:56.25%; position:relative; display:block; width: 100%"><iframe src="' . esc_url($response_text[1]) . '" width="100%" height="100%" style="position:absolute; top:0; left: 0" allowfullscreen webkitallowfullscreen frameborder="0"></iframe></div>',
                                    'output' => $response_text[1]
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to generate Stable Diffusion video in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => 'Video creation failed, please try again later.',
                                    'output' => 'Video creation failed, please try again later.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'image_url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'search_clickbank')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['query']))
                        {
                            $asin = $tc['function']['arguments']['query'];
                            if (empty($asin)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty search query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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 = 20;
                            }
                            $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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No ClickBank products found for query: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'An error occurred while searching ClickBank for: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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 = aiomatic_substr($final_result, 0, 400000);
                            $final_result = trim($final_result);
                            if(!empty($final_result))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $final_result
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'ClickBank did not return info for this query: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'query parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'search_amazon')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['query']))
                        {
                            $asin = $tc['function']['arguments']['query'];
                            if (empty($asin)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty search query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No Amazon products found for query: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'An error occurred while search Amazon for: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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 = aiomatic_substr($final_result, 0, 400000);
                            $final_result = trim($final_result);
                            if(!empty($final_result))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $final_result
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Amazon did not return info for this query: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'query parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'get_amazon_product_details')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['query']))
                        {
                            $asin = $tc['function']['arguments']['query'];
                            if (empty($asin)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty search query provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No Amazon products found for query: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(!is_array($amazresult))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'An error occurred while search Amazon for: ' . $asin
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $final_result
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'query parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'aimogen_content_editor_templates') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $operation = '';
                        if(isset($tc['function']['arguments']['operation']))
                        {
                            $operation = $tc['function']['arguments']['operation'];
                        }
                        $post_id = 0;
                        if(isset($tc['function']['arguments']['post_id']))
                        {
                            $post_id = intval($tc['function']['arguments']['post_id']);
                        }
                        if (!current_user_can('edit_post', $post_id)) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: not allowed'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $template_id = 0;
                        if(isset($tc['function']['arguments']['template_id']))
                        {
                            $template_id = intval($tc['function']['arguments']['template_id']);
                        }

                        if (empty($operation)) 
                        {
                            if(empty($post_id) || empty($template_id))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: operation parameter missing'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => aimogen_content_editor_templates_list()
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($post_id <= 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid post_id'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $post_obj = get_post($post_id);
                            if (!$post_obj) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Post not found'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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') 
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Invalid template_id'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                                $template_to_run = $template_id;
                            }

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

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => $template_id > 0 ? 'Template applied successfully' : 'Executed with default template logic'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Invalid operation'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'aimogen_rules_engine') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $operation = '';
                        if(isset($tc['function']['arguments']['operation']))
                        {
                            $operation = $tc['function']['arguments']['operation'];
                        }
                        $rule_id = '';
                        if(isset($tc['function']['arguments']['rule_id']))
                        {
                            $rule_id = $tc['function']['arguments']['rule_id'];
                        }
                        $rule_type = '';
                        if(isset($tc['function']['arguments']['rule_type']))
                        {
                            $rule_type = $tc['function']['arguments']['rule_type'];
                        }

                        if (empty($operation)) 
                        {
                            if(empty($rule_id) || empty($rule_type))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'operation missing'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => aimogen_rules_engine_list()
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($rule_id === null || $rule_type === null) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Missing rule_id or rule_type'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            if ($result === 'fail') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Execution failed'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if ($result === 'nochange') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No new content generated'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Rule executed successfully'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Invalid operation'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'edit_post_section') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $post_id    = isset($tc['function']['arguments']['post_id']) ? intval($tc['function']['arguments']['post_id']) : 0;
                        $selector   = isset($tc['function']['arguments']['section_selector']) ? sanitize_text_field($tc['function']['arguments']['section_selector']) : '';
                        $instruction = isset($tc['function']['arguments']['instruction']) ? trim(wp_kses_post($tc['function']['arguments']['instruction'])) : '';

                        if ($post_id <= 0 || $selector === '' || $instruction === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: post_id, section_selector and instruction are required.'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        
                        if (!current_user_can('edit_post', $post_id)) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: not allowed'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $post = get_post($post_id);

                        if (!$post) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Post with ID $post_id not found."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $content = $post->post_content;

                        if (trim($content) === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Post content is empty."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Failed to prepare post HTML."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Failed to parse post HTML."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

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

                        if (!$body) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Failed to locate parsed HTML body."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Could not locate section for selector '$selector'."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Failed extracting target content."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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 = AIMOGEN_DEFAULT_MODEL;    
                        $settings = get_option('aiomatic_Main_Settings', false);
                        $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)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: OpenAI API key is missing."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Not enough available tokens."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: AI error - $aierror"
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if (empty($edited)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: AI returned empty result."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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 === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: AI returned empty HTML after cleanup."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $fragment = $dom->createDocumentFragment();

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

                            $tmp->loadHTML('<div>' . $edited . '</div>');
                            libxml_clear_errors();

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

                            if (!$fragment->hasChildNodes()) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => "Error: Invalid HTML returned by AI."
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }

                        if ($selector === 'full_content') 
                        {
                            while ($body->firstChild) {
                                $body->removeChild($body->firstChild);
                            }
                            $body->appendChild($fragment);
                        } 
                        else 
                        {
                            if (!$target_node->parentNode) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => "Error: Target node has no parent."
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

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

                        $new_html = trim($new_html);

                        if ($new_html === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error: Edited content became empty."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Error updating post $post_id: " . $updated->get_error_message()
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => "Success: post ID $post_id updated."
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'list_available_ai_agents') 
                {
                    $toolOutputs[] = [
                        'tool_call_id' => $tc['id'], 
                        'output' => 'This tool is not supported'
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                    continue;
                }
                elseif ($tc['function']['name'] === 'delegate_to_ai_agent') 
                {
                    $toolOutputs[] = [
                        'tool_call_id' => $tc['id'], 
                        'output' => 'This tool is not supported'
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                    continue;
                }
                elseif ($tc['function']['name'] === 'read_server_file') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['file_path']))
                        {
                            $file_path = $tc['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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Access denied'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $ext = pathinfo($real_path, PATHINFO_EXTENSION);
                            if (!in_array($ext, array('txt', 'log', 'csv', 'json'))) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid file type'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if (!file_exists($real_path)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'File not found'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $content = substr(file_get_contents($real_path), 0, 5000);

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => $content
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'file_path parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'write_server_file') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['filename']) && isset($tc['function']['arguments']['content']))
                        {
                            $filename  = $tc['function']['arguments']['filename'];
                            $content   = $tc['function']['arguments']['content'];
                            $overwrite = isset($tc['function']['arguments']['overwrite']) ? (bool)$tc['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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid filename'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid file type'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            // 4. Size limit
                            if (strlen($content) > 2 * 1024 * 1024)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Content too large (max 2MB)'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid write path'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            // 6. Prevent overwrite
                            if (file_exists($target_path) && !$overwrite)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'File exists (overwrite not allowed)'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            // 7. JSON validation
                            if ($ext === 'json')
                            {
                                json_decode($content, true);
                                if (json_last_error() !== JSON_ERROR_NONE)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Invalid JSON content'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to write file'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Success: File saved at /wp-content/uploads/aiomatic-exports/' . basename($target_path)
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'filename or content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'get_wp_post_data') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['post_id']))
                        {
                            $post_id = $tc['function']['arguments']['post_id'];

                            if (empty($post_id)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: No Post ID provided.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $post = get_post($post_id);
                            if (!$post) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => "Error: Post with ID $post_id not found."
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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 ---";

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => aiomatic_substr($final_output, 0, 45000)
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'post_id parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'pause_execution') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['seconds']))
                        {
                            $seconds = (int)$tc['function']['arguments']['seconds'];

                            if ($seconds <= 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: seconds must be greater than 0.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            sleep($seconds);

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Waited $seconds seconds."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'seconds parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'wp_validate_post_state') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['post_id']) && isset($tc['function']['arguments']['checks']))
                        {
                            $post_id = $tc['function']['arguments']['post_id'];
                            $checks  = $tc['function']['arguments']['checks'];

                            if (empty($post_id)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: post_id is required.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if (!is_array($checks) || empty($checks)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: checks must be a non-empty array.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => implode("\n", $results)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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($tc['function']['arguments']['min_content_length']) ? (int)$tc['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 = $tc['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 = $tc['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);

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => $output
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'post_id or checks parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'wp_taxonomy_discovery') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['operation']))
                        {
                            $operation = $tc['function']['arguments']['operation'];

                            if (empty($operation)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: operation parameter was not provided.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if (!in_array($operation, array('list_taxonomies','list_terms','get_post_terms','create_term','set_post_terms'), true))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: Invalid operation parameter provided.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                                if (empty($taxonomies))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'No taxonomies found on this site.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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);

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => aiomatic_substr($output, 0, 45000)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }

                            // LIST TERMS
                            elseif ($operation === 'list_terms')
                            {
                                if(!isset($tc['function']['arguments']['taxonomy']))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'taxonomy parameter was not provided'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = $tc['function']['arguments']['taxonomy'];

                                if (!taxonomy_exists($taxonomy))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => "Error: Taxonomy $taxonomy does not exist."
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                if (is_wp_error($terms) || empty($terms))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => "No terms found for taxonomy: $taxonomy"
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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);

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => aiomatic_substr($output, 0, 45000)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }

                            // GET POST TERMS
                            elseif ($operation === 'get_post_terms')
                            {
                                if(!isset($tc['function']['arguments']['taxonomy']) || !isset($tc['function']['arguments']['post_id']))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'taxonomy or post_id parameter missing'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = $tc['function']['arguments']['taxonomy'];
                                $post_id  = $tc['function']['arguments']['post_id'];

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

                                if (empty($terms) || is_wp_error($terms))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => "No terms assigned."
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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);

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $output
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }

                            // CREATE TERM
                            elseif ($operation === 'create_term')
                            {
                                if(!isset($tc['function']['arguments']['taxonomy']) || !isset($tc['function']['arguments']['term_name']))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'taxonomy or term_name missing'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = $tc['function']['arguments']['taxonomy'];
                                $term_name = $tc['function']['arguments']['term_name'];

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

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

                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => "Term already exists. ID: $term_id"
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                if (is_wp_error($created))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => $created->get_error_message()
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => "Created term ID: " . $created['term_id']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            elseif ($operation === 'set_post_terms')
                            {
                                if (
                                    !isset($tc['function']['arguments']['taxonomy']) ||
                                    !isset($tc['function']['arguments']['post_id']) ||
                                    !isset($tc['function']['arguments']['term_name'])
                                )
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'taxonomy, post_id or term_name missing'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = sanitize_text_field($tc['function']['arguments']['taxonomy']);
                                $post_id  = intval($tc['function']['arguments']['post_id']);
                                $terms    = sanitize_text_field($tc['function']['arguments']['term_name']);

                                if (empty($taxonomy) || $post_id <= 0 || empty($terms))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Invalid taxonomy, post_id or term_name'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                if (!taxonomy_exists($taxonomy))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => "Taxonomy $taxonomy does not exist"
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'No valid terms to assign'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => "Success: Assigned " . count($term_ids) . " terms to post $post_id"
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'operation parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'get_environment_info') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['info_type']))
                        {
                            $type = sanitize_text_field($tc['function']['arguments']['info_type']);

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

                            if (!in_array($type, $allowed, true)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: Invalid info_type parameter.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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";
                            }

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => aiomatic_substr(trim($output), 0, 45000)
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'info_type parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'manage_wp_post') 
                {
                    if (!isset($tc['function']['arguments'])) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'],
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    $args = $tc['function']['arguments'];

                    if (!isset($args['operation']))
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'],
                            'output' => 'operation parameter was not provided'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    $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))
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'],
                            'output' => 'Error: Invalid operation. Allowed operations are: ' . implode(', ', $allowed_operations)
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    // --- CREATE ---
                    if ($operation === 'create')
                    {
                        if (empty($args['post_title']) || empty($args['post_content']))
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: Both post_title and post_content are required.'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $post_data = array(
                            '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)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: ' . $new_post_id->get_error_message()
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if (!empty($args['featured_image_id']))
                        {
                            set_post_thumbnail($new_post_id, intval($args['featured_image_id']));
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => "Success: Post created. ID: $new_post_id. URL: " . get_permalink($new_post_id)
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    // --- IDS ---
                    $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))
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'],
                            'output' => 'Error: ID or post_ids parameter is required.'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        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;
                        }

                        // --- UPDATE ---
                        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";
                        }

                        // --- FEATURED IMAGE ---
                        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();
                                    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";
                        }

                        // --- OTHER OPS ---
                        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($args['post_content'])) { $results[] = "Error content $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 content $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_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 = array_map('intval', array_filter(array_map('trim', explode(',', $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";
                        }
                    }

                    $toolOutputs[] = [
                        'tool_call_id' => $tc['id'],
                        'output' => implode("\n", $results)
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                }
                elseif ($tc['function']['name'] === 'search_site_posts') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $args_in = $tc['function']['arguments'];

                        $query_str   = isset($args_in['query']) ? $args_in['query'] : '';
                        $post_type   = !empty($args_in['post_type']) ? (array)$args_in['post_type'] : array('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 = 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($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 filter
                        if (!empty($args_in['author_id'])) {
                            $args['author'] = (int)$args_in['author_id'];
                        }

                        // date filter (FIXED)
                        if (!empty($args_in['date_after']) || !empty($args_in['date_before'])) 
                        {
                            $date_query = array();

                            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'] = array($date_query);
                        }

                        // taxonomy filter
                        if (!empty($args_in['taxonomy']) && !empty($args_in['terms'])) 
                        {
                            $terms = array_map('intval', explode(',', $args_in['terms']));

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

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

                        if (isset($args_in['has_featured_image'])) 
                        {
                            if ($args_in['has_featured_image'] === 'yes') {
                                $meta_query[] = array(
                                    'key'     => '_thumbnail_id',
                                    'compare' => 'EXISTS'
                                );
                            } elseif ($args_in['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 (limit 5)
                        if (!empty($args_in['meta_filters']) && is_string($args_in['meta_filters'])) 
                        {
                            $allowed_compares = ['=', '!=', '>', '>=', '<', '<=', 'LIKE', 'EXISTS', 'NOT EXISTS'];
                            $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] ?? '=');

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

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

                                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++;
                            }
                        }

                        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 = 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)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "No results found for the given filters."
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

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

                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => aiomatic_substr($output, 0, 30000)
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'wp_sideload_media') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['image_url']))
                        {
                            $image_url = $tc['function']['arguments']['image_url'];
                            $post_id = 0;
                            if(isset($tc['function']['arguments']['post_id']))
                            {
                                $post_id = $tc['function']['arguments']['post_id'];
                            }

                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: No image URL provided.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $result->get_error_message()
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => "Attachment ID: $result | URL: " . wp_get_attachment_url($result)
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'image_url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'get_wp_media_info') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['post_id']) || isset($tc['function']['arguments']['attachment_id']))
                        {
                            $post_id       = isset($tc['function']['arguments']['post_id']) ? intval($tc['function']['arguments']['post_id']) : 0;
                            $attachment_id = isset($tc['function']['arguments']['attachment_id']) ? intval($tc['function']['arguments']['attachment_id']) : 0;
                            $include_att   = isset($tc['function']['arguments']['include_attachments']) ? (bool)$tc['function']['arguments']['include_attachments'] : false;

                            $output = array();

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

                                if (!$attachment || $attachment->post_type !== 'attachment')
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Error: Attachment not found.'
                                    ];
                                    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']}";
                                }

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => implode("\n", $output)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                                if (!$post)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Error: Post not found.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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";
                                    }
                                }

                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => implode("\n", $output)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'post_id or attachment_id parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'get_post_structure') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        if(isset($tc['function']['arguments']['post_id']))
                        {
                            $post_id = intval($tc['function']['arguments']['post_id']);

                            if ($post_id <= 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: post_id is required.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $post = get_post($post_id);

                            if (!$post) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: Post not found.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $content = $post->post_content;

                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: Empty content.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            if (empty($html)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: Failed to normalize content.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error: Failed parsing HTML.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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
                            ]);

                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => $result
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'post_id parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode get_post_structure arguments: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['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) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Required plugin (Aimogen Extension Toubiz API) not activated.'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }
                    if (!function_exists('aiomatic_get_toubiz_api_results')) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Required plugin (Aimogen Extension Toubiz API) not correctly installed.'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }
                    $search = '';
                    if(isset($tc['function']['arguments']['search']))
                    {
                        $search =$tc['function']['arguments']['search'];
                    }
                    $date_after = '';
                    if(isset($tc['function']['arguments']['date_after']))
                    {
                        $date_after = $tc['function']['arguments']['date_after'];
                    }
                    $date_before = '';
                    if(isset($tc['function']['arguments']['date_before']))
                    {
                        $date_before = $tc['function']['arguments']['date_before'];
                    }
                    $type = '';
                    if(isset($tc['function']['arguments']['type']))
                    {
                        $type = $tc['function']['arguments']['type'];
                    }
                    $event_type = '';
                    if(isset($tc['function']['arguments']['event_type']))
                    {
                        $event_type = $tc['function']['arguments']['event_type'];
                    }
                    $rectangle_area = '';
                    if(isset($tc['function']['arguments']['rectangle_area']))
                    {
                        $rectangle_area = $tc['function']['arguments']['rectangle_area'];
                    }
                    $distance_from = '';
                    if(isset($tc['function']['arguments']['distance_from']))
                    {
                        $distance_from = $tc['function']['arguments']['distance_from'];
                    }
                    $languages = '';
                    if(isset($tc['function']['arguments']['languages']))
                    {
                        $languages = $tc['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) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Failed to access Toubiz API'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        aiomatic_log_to_file('Failed to access Toubiz API: ' . print_r($tc['function']['arguments'], true));
                    } 
                    else 
                    {
                        $toubiz_data = aiomatic_substr($toubiz_data, 0, 400000);
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => $toubiz_data
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'website_scraper')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['url']))
                        {
                            $scurl = $tc['function']['arguments']['url'];
                            if (empty($scurl) || !filter_var($scurl, FILTER_VALIDATE_URL)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid scrape url provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $parsed = parse_url($scurl);
                            if (!isset($parsed['scheme']) || !in_array(strtolower($parsed['scheme']), ['http', 'https']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Only http/https URLs are allowed'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)
                            ) {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Access to local/internal URLs is not allowed'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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']) == 'on')
                            {
                                $strip_tags = '1';
                            }
                            else
                            {
                                $strip_tags = '0';
                            }
                            $scraped_data = aiomatic_scrape_page($scurl, $scrape_method, $scrape_selector, $scrape_string);
                            if($scraped_data === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to scrape website URL: ' . $scurl
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                            }
                            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);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $scraped_data
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'rss_feed_parser')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['url']))
                        {
                            $scurl = $tc['function']['arguments']['url'];
                            if (empty($scurl)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty RSS feed URL provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to load RSS parser library'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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()) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error in parsing RSS feed: ' . $feed->error()
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $final_result = '';
                            $items = $feed->get_items();
                            foreach($items as $itemx)
                            {
                                $post_link = trim($itemx->get_permalink());
                                if ($fauthor = $itemx->get_author()) 
                                {
                                    $user_name = $fauthor->get_name();
                                }
                                else
                                {
                                    $user_name = '';
                                }
                                $feed_cats = array();
                                foreach ($itemx->get_categories() as $xcategory)
                                {
                                    $feed_cats[] = $xcategory->get_label();
                                }
                                $post_cats = implode(',', $feed_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($final_result === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse RSS URL (no data returned): ' . $scurl
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                            }
                            else
                            {
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $final_result
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'google_results_parser')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['keywords']))
                        {
                            $keywords = $tc['function']['arguments']['keywords'];
                            if (empty($keywords)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty keywords parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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($final_res === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Google SERP for keyword (no data returned): ' . $keywords
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                            }
                            else
                            {
                                $final_res = aiomatic_substr($final_res, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $final_res
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'keywords parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'royalty_free_image_search')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['keyword']))
                        {
                            $raw_img_list = array();
                            $full_result_list = array();
                            $keyword = $tc['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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty keyword parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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($temp_get_img === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to get royalty free image for keyword: ' . $keyword
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($temp_get_img) . '">',
                                    'output' => $temp_get_img
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'keyword parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'lead_capture')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['email']))
                        {
                            $raw_img_list = array();
                            $full_result_list = array();
                            $name = '';
                            $phone_number = '';
                            $job_title = '';
                            $company_name = '';
                            $location = '';
                            $birth_date = '';
                            $how_you_found_us = '';
                            $website_url = '';
                            $preferred_contact_method = '';
                            $email = $tc['function']['arguments']['email'];
                            if (empty($email)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty email parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(isset($tc['function']['arguments']['name']))
                            {
                                $name = $tc['function']['arguments']['name'];
                            }
                            if(isset($tc['function']['arguments']['phone_number']))
                            {
                                $phone_number = $tc['function']['arguments']['phone_number'];
                            }
                            if(isset($tc['function']['arguments']['job_title']))
                            {
                                $job_title = $tc['function']['arguments']['job_title'];
                            }
                            if(isset($tc['function']['arguments']['company_name']))
                            {
                                $company_name = $tc['function']['arguments']['company_name'];
                            }
                            if(isset($tc['function']['arguments']['location']))
                            {
                                $location = $tc['function']['arguments']['location'];
                            }
                            if(isset($tc['function']['arguments']['birth_date']))
                            {
                                $birth_date = $tc['function']['arguments']['birth_date'];
                            }
                            if(isset($tc['function']['arguments']['how_you_found_us']))
                            {
                                $how_you_found_us = $tc['function']['arguments']['how_you_found_us'];
                            }
                            if(isset($tc['function']['arguments']['website_url']))
                            {
                                $website_url = $tc['function']['arguments']['website_url'];
                            }
                            if(isset($tc['function']['arguments']['preferred_contact_method']))
                            {
                                $preferred_contact_method = $tc['function']['arguments']['preferred_contact_method'];
                            }
                            $lead_result = aiomatic_save_lead_data(
                                $email,
                                $name,
                                $phone_number,
                                $job_title,
                                $company_name,
                                $location,
                                $birth_date,
                                $how_you_found_us,
                                $website_url,
                                $preferred_contact_method
                            );
                            if($lead_result === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error! Failed to save the lead data.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Lead data saved successfully.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'email parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'query_wp_database')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['query']))
                        {
                            $query = $tc['function']['arguments']['query'];
                            if (empty($query)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty query parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => "Query type '$query_type' is not allowed. Allowed types: " . implode(', ', $allowed_commands)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Error! Invalid query or no results found.'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                } 
                                else
                                {
                                    if ($query_type === 'SELECT' && count($lead_result) > 500) {
                                        $lead_result = array_slice($lead_result, 0, 500);
                                    }
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => json_encode($lead_result)
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                            } 
                            catch (Exception $e) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Error executing the query: ' . $e->getMessage()
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'query parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'aimogen_execute_omniblock_rule') 
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['omniblock_id']))
                        {
                            if(isset($tc['function']['arguments']['input_parameters']))
                            {
                                $input_text = $tc['function']['arguments']['input_parameters'];
                            }
                            else
                            {
                                $input_text = '';
                            }
                            $omniblock_id = $tc['function']['arguments']['omniblock_id'];
                            if (empty($omniblock_id)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty omniblock_id parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'This OmniBlock ID does not exist in the configured rules'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No OmniBlock rules configured in settings'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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]))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Incorrect OmniBlock ID submitted in request'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(count($id_parts) > 2)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Incorrect format for OmniBlock IDs'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $param = $id_parts[0];
                            $omniTriggerID = $id_parts[1];
                            $rules = get_option('aiomatic_omni_list', array());
                            $found = false;
                            if (!empty($rules)) 
                            {
                                $default_block_types = aiomatic_omniblocks_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);
                                                    }
                                                    $toolOutputs[] = [
                                                        'tool_call_id' => $tc['id'], 
                                                        'output' => wp_kses_post($return_me)
                                                    ];
                                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                                    $found = true;
                                                    break 2;
                                                }
                                            }
                                        }
                                    }
                                    $cont = $cont + 1;
                                }
                                if($found == false)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => 'Specified \'AI Chatbot Trigger\' OmniBlock ID not found: ' . $omniblock_id
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No rules found for aiomatic_omni_list!'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            continue;
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'omniblock_id argument not set for the function call'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'generate_ai_model_reasoning')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['prompt']))
                        {
                            $prompt = $tc['function']['arguments']['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty prompt parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $model = '';
                            if(isset($tc['function']['arguments']['model']))
                            {
                                $model = $tc['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))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => '[ERROR] API key not configured in plugin settings.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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 = '';
                            $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(), '', '', '');
                            if($generated_text === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => '[ERROR] Failed to generate content using AI writer: ' . $model . ' - error: ' . $aierror
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $new_post_content = aiomatic_sanitize_ai_result($generated_text);
                                if(empty($new_post_content))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => '[ERROR] No content returned by the AI writer!'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                                else
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $tc['id'], 
                                        'output' => $new_post_content
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'youtube_video_captions')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['url']))
                        {
                            $zurl = $tc['function']['arguments']['url'];
                            $zurl = aiomatic_extractYouTubeVideoId($zurl);
                            if (empty($zurl)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty url parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to find subtitles for video URL: ' . $zurl
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            if(!empty($max_caption) && aiomatic_strlen($returned_caption) > $max_caption)
                            {
                                $returned_caption = aiomatic_substr($returned_caption, 0, $max_caption);
                            }
                            if($returned_caption == '')
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse YouTube video caption for URL (no data returned): ' . $zurl
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                            }
                            else
                            {
                                $returned_caption = aiomatic_substr($returned_caption, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => $returned_caption
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'youtube_video_search')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['keyword']))
                        {
                            $keyword = $tc['function']['arguments']['keyword'];
                            if (empty($keyword)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty keyword parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $new_vid = aiomatic_get_video($keyword, '', array());
                            if($new_vid == '')
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse YouTube video search results for keyword (no data returned): ' . $keyword
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'echo' => $new_vid,
                                    'output' => $new_vid
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'keyword parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_facebook_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (F-omatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $furl = '';
                            if(isset($tc['function']['arguments']['url']))
                            {
                                $furl = $tc['function']['arguments']['url'];
                            }
                            $zcontent = $tc['function']['arguments']['content'];
                            if (empty($zcontent)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No page where to publish the post was selected'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Facebook posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Facebook posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Facebook posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_facebook_image')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['image_url']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (F-omatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $caption = '';
                            if(isset($tc['function']['arguments']['caption']))
                            {
                                $caption = $tc['function']['arguments']['caption'];
                            }
                            $image_url = $tc['function']['arguments']['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty image_url parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No page where to publish the post was selected'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Facebook image posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Facebook image posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Facebook image posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'image_url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_twitter_x_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Twitomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $image_url = '';
                            if(isset($tc['function']['arguments']['image_url']))
                            {
                                $image_url = $tc['function']['arguments']['image_url'];
                            }
                            $zcontent = $tc['function']['arguments']['content'];
                            if (empty($zcontent)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Twitter posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Twitter posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Twitter posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_threads_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Threadsomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $image_url = '';
                            if(isset($tc['function']['arguments']['image_url']))
                            {
                                $image_url = $tc['function']['arguments']['image_url'];
                            }
                            $zcontent = $tc['function']['arguments']['content'];
                            if (empty($zcontent)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Threads posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Threads posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Threads posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_instagram_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['image_url']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Instamatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $zcontent = '';
                            if(isset($tc['function']['arguments']['content']))
                            {
                                $zcontent = $tc['function']['arguments']['content'];
                            }
                            $image_url = $tc['function']['arguments']['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty image_url parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            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, $zcontent, $image_url);
                            if(isset($return_me['error']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Instagram posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Instagram posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Instagram posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'image_url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_pinterest_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['image_url']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Pinterestomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No boards where to publish the post was selected'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $description = '';
                            if(isset($tc['function']['arguments']['description']))
                            {
                                $description = $tc['function']['arguments']['description'];
                            }
                            $title = '';
                            if(isset($tc['function']['arguments']['title']))
                            {
                                $title = $tc['function']['arguments']['title'];
                            }
                            $pin_url = '';
                            if(isset($tc['function']['arguments']['pin_url']))
                            {
                                $pin_url = $tc['function']['arguments']['pin_url'];
                            }
                            $image_url = $tc['function']['arguments']['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty image_url parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Pinterest posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Pinterest posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Pinterest posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'image_url parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_google_my_business_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['image_url']) && isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Businessomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No pages where to publish the post was selected'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $content = $tc['function']['arguments']['content'];
                            $image_url = $tc['function']['arguments']['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty image_url parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'GMB posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse GMB posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'GMB posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'image_url or content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_youtube_community_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['post_type']) && isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Youtubomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $content = $tc['function']['arguments']['content'];
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $post_type = $tc['function']['arguments']['post_type'];
                            if (empty($post_type)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty post_type parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $post_type = trim($post_type);
                            if($post_type != 'image' && $post_type != 'text')
                            {
                                $post_type = 'text';
                            }
                            $image_url = '';
                            if(isset($tc['function']['arguments']['image_url']))
                            {
                                $image_url = $tc['function']['arguments']['image_url'];
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            if($image_url != '')
                            {
                                $media = array($image_url);
                            }
                            else
                            {
                                $media = array();
                            }
                            $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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'YouTube Community posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse YouTube Community posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'YouTube Community posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'post_type or content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_reddit_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['title']) && isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Redditomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $content = $tc['function']['arguments']['content'];
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $title = $tc['function']['arguments']['title'];
                            if (empty($title)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty title parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No subreddits were defined where to publish the post'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            if($image_url != '')
                            {
                                $media = array($image_url);
                            }
                            else
                            {
                                $media = array();
                            }
                            $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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Reddit posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse Reddit posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Reddit posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'title or content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'publish_linkedin_post')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['title']) && isset($tc['function']['arguments']['content']))
                        {
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Required plugin (Linkedinomatic) not activated.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $content = $tc['function']['arguments']['content'];
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty content parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $title = $tc['function']['arguments']['title'];
                            if (empty($title)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty title parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $description = '';
                            $post_link = '';
                            $image_url = '';
                            if(isset($tc['function']['arguments']['description']))
                            {
                                $description = $tc['function']['arguments']['description'];
                            }
                            if(isset($tc['function']['arguments']['link']))
                            {
                                $post_link = $tc['function']['arguments']['link'];
                            }
                            if(isset($tc['function']['arguments']['image_url']))
                            {
                                $image_url = $tc['function']['arguments']['image_url'];
                            }
                            $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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'No pages selected where to post to LinkedIn'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'LinkedIn posting failed: ' . $return_me['error']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            elseif(empty($return_me))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to parse LinkedIn posting results'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'LinkedIn posting successful: ' . json_encode($return_me, true)
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'title or content parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'wp_send_email')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['subject']) && isset($tc['function']['arguments']['content']) && isset($tc['function']['arguments']['recipient_email']))
                        {
                            $subject = $tc['function']['arguments']['subject'];
                            $content = $tc['function']['arguments']['content'];
                            $recipient_email = $tc['function']['arguments']['recipient_email'];
                            if (empty($subject) || empty($content) || empty($recipient_email)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty subject, content or recipient_email parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $admin_mail = get_option('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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to send email to address: ' . $recipient_email
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'OK'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'subject, content or recipient_email parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($tc['function']['name'] === 'call_webhook')
                {
                    if (isset($tc['function']['arguments'])) 
                    {
                        $result = '';
                        if(isset($tc['function']['arguments']['webhook_url']) && isset($tc['function']['arguments']['method_selector']))
                        {
                            $webhook_url = $tc['function']['arguments']['webhook_url'];
                            $webhook_method = $tc['function']['arguments']['webhook_method'];
                            $method_selector = $tc['function']['arguments']['method_selector'];
                            if (empty($webhook_url) || empty($method_selector)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty webhook_url or method_selector parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if (empty($webhook_method)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Empty webhook_method parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $content_type = '';
                            if(isset($tc['function']['arguments']['content_type']))
                            {
                                $content_type = $tc['function']['arguments']['content_type'];
                            }
                            $post_template = '';
                            if(isset($tc['function']['arguments']['data']))
                            {
                                $post_template = $tc['function']['arguments']['data'];
                            }
                            $headers_template = '';
                            if(isset($tc['function']['arguments']['headers']))
                            {
                                $headers_template = $tc['function']['arguments']['headers'];
                            }
                            
                            $urlParsed = wp_parse_url( $webhook_url, PHP_URL_HOST );
                            if ( filter_var( $webhook_url, FILTER_VALIDATE_URL ) === FALSE || empty( $urlParsed ) )
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Invalid webhook_url entered ' . $webhook_url
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else if ( $content_type == 'JSON' && empty( json_decode( $post_template, TRUE ) ) )
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'The JSON data must be valid ' . $webhook_url
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to init curl in webhook execution'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Failed to send webhook request to ' . $webhook_url
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $err = curl_error($ch);
                            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);
                            if ($err) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Webhook request error to URL ' . $webhook_url . ' - error: ' . $err
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if ($statusCode >= 200 && $statusCode <= 299) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Webhook URL called successfully!'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $tc['id'], 
                                    'output' => 'Webhook unexpected return code to URL ' . $webhook_url . ' - return code: ' . $statusCode
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'subject, content or recipient_email parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($tc, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $tc['id'], 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
            }
        }
    } else {
        throw new Exception("Required action details are missing or incomplete.");
    }
    return $toolOutputs;
}
function aiomatic_call_ollama_tool($response) 
{
    $toolOutputs = [];
    if (isset($response['message']['tool_calls'])) 
    {
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        require_once(__DIR__ . '/res/amazon-direct.php');
        foreach ($response['message']['tool_calls'] as $zid => $tc) 
        {
            if (isset($tc['function'])) 
            {
                $function_name = $tc['function']['name'] ?? '';
                $arguments = $tc['function']['arguments'] ?? [];
                if (!aiomatic_is_restricted_function_allowed($function_name)) {
                    aiomatic_log_to_file('Blocked tool (central filter): ' . $function_name);
                    $toolOutputs[] = [
                        'tool_call_id' => $zid, 
                        'output' => 'You are not allowed to call this function (not admin)',
                        'message' => $response['message']
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                    continue;
                }
                if ($function_name === 'aimogen_wp_god_mode') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['called_function_name'])) 
                        {
                            $function_name = $arguments['called_function_name'];
                            $params = $arguments['parameter_array'] ?? [];
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            if (isset($aiomatic_Chatbot_Settings['god_whitelisted_functions']) && trim($aiomatic_Chatbot_Settings['god_whitelisted_functions']) != '') 
                            {
                                $white = array_filter(preg_split('/\r\n|\r|\n/', trim($aiomatic_Chatbot_Settings['god_whitelisted_functions'])));
                                if (!in_array($function_name, $white)) 
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] === 'on') 
                                    {
                                        aiomatic_log_to_file('Function call not allowed (Ollama), not whitelisted: ' . $function_name);
                                    }
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'You are not allowed to call this function (not on the whitelisted functions list)',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                            }
                            if (aiomatic_is_god_mode_function_blacklisted($function_name, $aiomatic_Chatbot_Settings)) 
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] === 'on') 
                                {
                                    aiomatic_log_to_file('Function call not allowed (Ollama), blacklisted: ' . $function_name);
                                }
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'You are not allowed to call this function (on the blacklisted functions list)',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if (function_exists($function_name)) 
                            {
                                if (!is_array($params)) 
                                {
                                    $jsony = json_decode($params, true);
                                    $params = $jsony !== null ? $jsony : (empty($params) ? [] : [$params]);
                                }
                                if (isset($params['post_title']) && $function_name === 'wp_insert_post') 
                                {
                                    $params = [$params];
                                }

                                $paramsAsString = aiomatic_format_function_params($params);
                                try {
                                    $reflection = new ReflectionFunction($function_name);
                                    $requiredParamsCount = $reflection->getNumberOfRequiredParameters();

                                    if (is_numeric($requiredParamsCount) && $requiredParamsCount > 0 && count($params) < $requiredParamsCount) 
                                    {
                                        $result = $function_name . ' function has ' . $requiredParamsCount . ' required parameters, but only ' . count($params) . ' were passed to it.';
                                    } 
                                    else 
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] === 'on') 
                                        {
                                            aiomatic_log_to_file('Calling function (Ollama) ' . $function_name . '(' . $paramsAsString . ')...');
                                        }
                                        $result = call_user_func_array($function_name, $params);
                                    }
                                } catch (Throwable $e) {
                                    $result = 'Invalid function: ' . $function_name;
                                }
                            } 
                            else 
                            {
                                $result = $function_name . ' function was not found on the system.';
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] === 'on') 
                            {
                                $paramsAsString = aiomatic_format_function_params($params);
                                if ($result === false) 
                                {
                                    aiomatic_log_to_file('Function (Ollama) ' . $function_name . '(' . $paramsAsString . ') - returned false');
                                    $result = $function_name . ' returned false';
                                } 
                                elseif (empty($result)) 
                                {
                                    aiomatic_log_to_file('Function (Ollama) ' . $function_name . '(' . $paramsAsString . ') - returned an empty response: ' . print_r($result, true));
                                    $result = $function_name . ' returned an empty response';
                                } 
                                else 
                                {
                                    aiomatic_log_to_file('Function (Ollama) ' . $function_name . '(' . $paramsAsString . ') - result: ' . print_r($result, true));
                                }
                            }
                            if (is_object($result) || is_array($result)) 
                            {
                                $result = json_encode($result);
                                if ($result === false) {
                                    $result = 'Failed to encode tool result.';
                                }
                            }
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => (string) $result,
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'called_function_name parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'end_chatbot_conversation') 
                {
                    $toolOutputs[] = [
                        'tool_call_id' => $zid, 
                        'echo' => 'AiomaticConversationEnded~!@#$%^&*()',
                        'output' => 'Conversation ended',
                        'message' => $response['message']
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                }
                elseif ($function_name === 'generate_chart') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['shortcode'])) 
                        {
                            $shortcode = $arguments['shortcode'];
                            $result = do_shortcode($shortcode);
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'echo' => $result,
                                'output' => $result,
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'generate_ai_image_openai') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            
                            if (!isset($aiomatic_Main_Settings['app_id'])) 
                            {
                                $aiomatic_Main_Settings['app_id'] = '';
                            }
                            
                            $appids = array_filter(preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id'])));
                            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!');
                                $errorMessage = $aiomatic_Chatbot_Settings['god_mode_dalle_failed'] ?? 'Image creation failed, please try again later.';
                                
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => $errorMessage,
                                    'output' => $errorMessage,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            
                            $image_size = $aiomatic_Chatbot_Settings['ai_image_size'] ?? '512x512';
                            $model = $aiomatic_Chatbot_Settings['ai_image_model'] ?? 'gpt-image-2';
                            $aierror = '';
                            
                            $result = aiomatic_generate_ai_image($token, 1, $prompt, $image_size, 'chatFunctionDalleImage', false, 0, $aierror, $model, $prompt);
                            
                            if ($result !== false && is_array($result)) 
                            {
                                foreach ($result as $tmpimg) 
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($tmpimg) . '">',
                                        'output' => $tmpimg,
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    break;
                                }
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Dall-E image in AI chatbot: ' . $aierror);
                                $errorMessage = $aiomatic_Chatbot_Settings['god_mode_dalle_failed'] ?? 'Image creation failed, please try again later.';
                                
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => $errorMessage,
                                    'output' => $errorMessage,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'generate_ai_image_stable_diffusion') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $image_size = $aiomatic_Chatbot_Settings['ai_image_size_stable'] ?? '512x512';
                            $height = $width = '512';
                            
                            if ($image_size === '1024x1024') 
                            {
                                $height = $width = '1024';
                            }
                            
                            $model = $aiomatic_Chatbot_Settings['stable_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])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult[1]) . '">',
                                    'output' => $airesult[1],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Stable Diffusion image in AI chatbot: ' . $aierror);
                                $errorMessage = $aiomatic_Chatbot_Settings['god_mode_stable_failed'] ?? 'Image creation failed, please try again later.';
                                
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => $errorMessage,
                                    'output' => $errorMessage,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'generate_ai_image_google') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult[1]) . '">',
                                    'output' => $airesult[1],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Stable Diffusion image in AI chatbot: ' . $aierror);
                                $errorMessage = $aiomatic_Chatbot_Settings['god_mode_stable_failed'] ?? 'Image creation failed, please try again later.';
                                
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => $errorMessage,
                                    'output' => $errorMessage,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'generate_ai_image_midjourney') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_ai_image_midjourney($prompt, $width, $height, 'chatFunctionMidjourneyImage', false, $aierror);
                            
                            if ($airesult !== false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Midjourney image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'generate_ai_image_replicate') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_replicate_image($prompt, $width, $height, 'chatFunctionReplicateImage', false, $aierror);
                            
                            if ($airesult !== false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Replicate image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'generate_ai_image_ideogram') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_ideogram_image($prompt, $width, $height, 'chatFunctionIdeogramImage', false, $aierror);
                            
                            if ($airesult !== false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Ideogram image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'generate_ai_image_cloudflare') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['prompt'])) 
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $height = '1024';
                            $width = '1024';
                            $aierror = '';
                            $airesult = aiomatic_generate_cloudflare_image($prompt, $width, $height, 'chatFunctionCloudflareImage', false, $aierror);
                            
                            if ($airesult !== false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($airesult) . '">',
                                    'output' => $airesult,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Cloudflare image in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => 'Image creation failed, please try again later.',
                                    'output' => 'Image creation failed, please try again later.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'manage_booking_calendar_booking') 
                {
                    if (!empty($arguments)) 
                    {
                        if (empty($arguments['start_date']) || empty($arguments['end_date']) || empty($arguments['name']) || empty($arguments['email'])) {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output'       => 'Missing required booking parameters (start_date, end_date, name, email).',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $start_date  = sanitize_text_field($arguments['start_date']);
                        $end_date    = sanitize_text_field($arguments['end_date']);
                        $start_ts = strtotime($start_date);
                        $end_ts   = strtotime($end_date);
                        if (!$start_ts || !$end_ts || $end_ts < $start_ts) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'A valid date range is required.',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $name        = sanitize_text_field($arguments['name']);
                        $email       = sanitize_email($arguments['email']);
                        if (!is_email($email)) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'],
                                'output'       => 'A valid email is required.',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $secondname  = isset($arguments['secondname']) ? sanitize_text_field($arguments['secondname']) : '';
                        $resource_id = isset($arguments['resource_id']) ? intval($arguments['resource_id']) : 1;

                        if (!function_exists('wpbc_api_is_dates_booked') || !function_exists('wpbc_api_booking_add_new')) {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output'       => 'Booking Calendar API functions are not available.',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output'       => 'These dates are already booked, select different dates',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output'       => 'Booking created: ' . $booking_id,
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } else {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output'       => 'Failed to create booking.',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output'       => 'Arguments not set for the booking function call.',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'create_stable_diffusion_video') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['image_url'])) 
                        {
                            $image_url = $arguments['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty image_url query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $image_size = $aiomatic_Chatbot_Settings['ai_video_size_stable'] ?? '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])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<div style="padding-bottom:56.25%; position:relative; display:block; width: 100%"><iframe src="' . esc_url($response_text[1]) . '" width="100%" height="100%" style="position:absolute; top:0; left: 0" allowfullscreen webkitallowfullscreen frameborder="0"></iframe></div>',
                                    'output' => $response_text[1],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                aiomatic_log_to_file('Failed to generate Stable Diffusion video in AI chatbot: ' . $aierror);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => 'Video creation failed, please try again later.',
                                    'output' => 'Video creation failed, please try again later.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'image_url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'search_clickbank') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['query'])) 
                        {
                            $asin = $arguments['query'];
                            if (empty($asin)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty search query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            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%%';
                            }
                            // Handle the max product count range
                            if (strstr($max_product_count, '-') !== false) 
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                $max_product_count = (is_numeric($minx) && is_numeric($maxx)) ? rand(intval($minx), intval($maxx)) : (is_numeric($minx) ? intval($minx) : (is_numeric($maxx) ? intval($maxx) : 100));
                            }
                            $max_prod = is_numeric($max_product_count) ? intval($max_product_count) : 20;
                
                            $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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No ClickBank products found for query: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if (!is_array($amazresult)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'An error occurred while searching ClickBank for: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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);
                                // Additional replacements
                                $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 = aiomatic_substr($final_result, 0, 400000);
                            $final_result = trim($final_result);
                            if (!empty($final_result)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $final_result,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'ClickBank did not return info for this query: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'query parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'search_amazon') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['query'])) 
                        {
                            $asin = $arguments['query'];
                            if (empty($asin)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty search query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $aff_id = $aiomatic_Chatbot_Settings['affiliate_id'] ?? '';
                            $target_country = $aiomatic_Chatbot_Settings['target_country'] ?? 'com';
                            $max_product_count = $aiomatic_Chatbot_Settings['max_products'] ?? '3-4';
                            $amaz_sort_results = $aiomatic_Chatbot_Settings['sort_results'] ?? 'none';
                            $listing_template = $aiomatic_Chatbot_Settings['listing_template'] ?? '%%product_counter%%. %%product_title%% - Description: %%product_description%% - Link: %%product_url%% - Price: %%product_price%%';
                
                            // Handle the max product count range
                            if (strstr($max_product_count, '-') !== false) 
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                $max_product_count = (is_numeric($minx) && is_numeric($maxx)) ? rand(intval($minx), intval($maxx)) : (is_numeric($minx) ? intval($minx) : (is_numeric($maxx) ? intval($maxx) : 100));
                            }
                            $max_prod = is_numeric($max_product_count) ? intval($max_product_count) : 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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No Amazon products found for query: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if (!is_array($amazresult)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'An error occurred while searching Amazon for: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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);
                                // Additional replacements
                                $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 = aiomatic_substr($final_result, 0, 400000);
                            $final_result = trim($final_result);
                            if (!empty($final_result)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $final_result,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Amazon did not return info for this query: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'query parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'get_amazon_product_details') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['query'])) 
                        {
                            $asin = $arguments['query'];
                            if (empty($asin)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty search query provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $aff_id = $aiomatic_Chatbot_Settings['affiliate_id'] ?? '';
                            $target_country = $aiomatic_Chatbot_Settings['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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No Amazon products found for query: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if (!is_array($amazresult)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'An error occurred while searching Amazon for: ' . $asin,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else 
                            {
                                $product = $amazresult[0];
                                $final_result = 'Product title: ' . $product->offer_title . '\n';
                                $final_result .= 'Description: ' . $product->offer_desc . '\n';
                                $final_result .= 'URL: ' . $product->offer_url . '\n';
                                $final_result .= 'Price: ' . $product->offer_price . '\n';
                                $final_result .= 'Listing Price: ' . $product->product_list_price . '\n';
                                $final_result .= 'Image: ' . $product->offer_img . '\n';
                                $final_result .= 'Add to cart URL: ' . $product->cart_url . '\n';
                                $final_result .= 'Other images: ' . $product->product_imgs . '\n';
                
                                // Additional details
                                if (!empty($product->item_score)) 
                                {
                                    $final_result .= 'Score: ' . $product->item_score . '\n';
                                }
                                if (!empty($product->language)) 
                                {
                                    $final_result .= 'Language: ' . $product->language . '\n';
                                }
                                if (!empty($product->edition)) 
                                {
                                    $final_result .= 'Edition: ' . $product->edition . '\n';
                                }
                                if (!empty($product->pages_count)) 
                                {
                                    $final_result .= 'Pages Count: ' . $product->pages_count . '\n';
                                }
                                if (!empty($product->publication_date)) 
                                {
                                    $final_result .= 'Date: ' . $product->publication_date . '\n';
                                }
                                if (!empty($product->contributors)) 
                                {
                                    $final_result .= 'Contributors: ' . $product->contributors . '\n';
                                }
                                if (!empty($product->manufacturer)) 
                                {
                                    $final_result .= 'Manufacturer: ' . $product->manufacturer . '\n';
                                }
                                if (!empty($product->binding)) 
                                {
                                    $final_result .= 'Binding: ' . $product->binding . '\n';
                                }
                                if (!empty($product->product_group)) 
                                {
                                    $final_result .= 'Product Group: ' . $product->product_group . '\n';
                                }
                                if (!empty($product->rating)) 
                                {
                                    $final_result .= 'Rating: ' . $product->rating . '\n';
                                }
                                if (!empty($product->eans)) 
                                {
                                    $final_result .= 'EAN: ' . $product->eans . '\n';
                                }
                                if (!empty($product->part_no)) 
                                {
                                    $final_result .= 'Part No: ' . $product->part_no . '\n';
                                }
                                if (!empty($product->model)) 
                                {
                                    $final_result .= 'Model: ' . $product->model . '\n';
                                }
                                if (!empty($product->warranty)) 
                                {
                                    $final_result .= 'Warranty: ' . $product->warranty . '\n';
                                }
                                if (!empty($product->color)) 
                                {
                                    $final_result .= 'Color: ' . $product->color . '\n';
                                }
                                if (!empty($product->is_adult)) 
                                {
                                    $final_result .= 'Is Adult: ' . $product->is_adult . '\n';
                                }
                                if (!empty($product->dimensions)) 
                                {
                                    $final_result .= 'Dimensions: ' . $product->dimensions . '\n';
                                }
                                if (!empty($product->size)) 
                                {
                                    $final_result .= 'Size: ' . $product->size . '\n';
                                }
                                if (!empty($product->unit_count)) 
                                {
                                    $final_result .= 'Unit Count: ' . $product->unit_count . '\n';
                                }
                                $final_result .= 'Reviews: ' . implode(PHP_EOL, $product->item_reviews) . '\n';
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $final_result,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'query parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'aimogen_content_editor_templates') 
                {
                    if (!empty($arguments)) 
                    {
                        $operation = '';
                        if(isset($arguments['operation']))
                        {
                            $operation = $arguments['operation'];
                        }
                        $post_id = 0;
                        if(isset($arguments['post_id']))
                        {
                            $post_id = intval($arguments['post_id']);
                        }
                        if (!current_user_can('edit_post', $post_id)) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: not allowed'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        $template_id = 0;
                        if(isset($arguments['template_id']))
                        {
                            $template_id = intval($arguments['template_id']);
                        }

                        if (empty($operation)) 
                        {
                            if(empty($post_id) || empty($template_id))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: operation parameter missing',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => aimogen_content_editor_templates_list(),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($post_id <= 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid post_id',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $post_obj = get_post($post_id);
                            if (!$post_obj) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Post not found',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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') 
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Invalid template_id',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                                $template_to_run = $template_id;
                            }

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

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => $template_id > 0 ? 'Template applied successfully' : 'Executed with default template logic',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Invalid operation',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'aimogen_rules_engine') 
                {
                    if (!empty($arguments)) 
                    {
                        $operation = '';
                        if(isset($arguments['operation']))
                        {
                            $operation = $arguments['operation'];
                        }
                        $rule_id = '';
                        if(isset($arguments['rule_id']))
                        {
                            $rule_id = $arguments['rule_id'];
                        }
                        $rule_type = '';
                        if(isset($arguments['rule_type']))
                        {
                            $rule_type = $arguments['rule_type'];
                        }

                        if (empty($operation)) 
                        {
                            if(empty($rule_id) || empty($rule_type))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'operation missing',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $operation = 'run';
                        }

                        if ($operation === 'list') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => aimogen_rules_engine_list(),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if ($operation === 'run') 
                        {
                            if ($rule_id === null || $rule_type === null) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Missing rule_id or rule_type',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            if ($result === 'fail') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Execution failed',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if ($result === 'nochange') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No new content generated',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'Rule executed successfully',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Invalid operation',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'edit_post_section') 
                {
                    if (!empty($arguments)) 
                    {
                        $post_id    = isset($arguments['post_id']) ? intval($arguments['post_id']) : 0;
                        $selector   = isset($arguments['section_selector']) ? sanitize_text_field($arguments['section_selector']) : '';
                        $instruction = isset($arguments['instruction']) ? trim(wp_kses_post($arguments['instruction'])) : '';
                        
                        if (!current_user_can('edit_post', $post_id)) {
                            $toolOutputs[] = [
                                'tool_call_id' => $tc['id'], 
                                'output' => 'Error: not allowed',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }
                        if ($post_id <= 0 || $selector === '' || $instruction === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'Error: post_id, section_selector and instruction are required.',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $post = get_post($post_id);

                        if (!$post) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Post with ID $post_id not found.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $content = $post->post_content;

                        if (trim($content) === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Post content is empty.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Failed to prepare post HTML.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Failed to parse HTML.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

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

                        if (!$body) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Missing body node.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            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) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Could not locate section '$selector'.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $target_html = ($selector === 'full_content')
                            ? implode('', array_map([$dom, 'saveHTML'], iterator_to_array($body->childNodes)))
                            : $dom->saveHTML($target_node);

                        if (trim($target_html) === '') 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Error: Failed extracting content.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $prompt = "Edit HTML:

                Instruction:
                {$instruction}

                CONTENT:
                {$target_html}

                Return ONLY HTML.";

                        $model = AIMOGEN_DEFAULT_MODEL;
                        $settings = get_option('aiomatic_Main_Settings', false);
                        $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 (!$token) {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output' => "Error: Missing API key.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $available_tokens = aimogenpro_get_max_tokens($model) - count(aiomatic_encode($prompt));

                        $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
                        );

                        if ($aierror || !$edited) {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output' => "Error: AI failed.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $edited = trim(preg_replace('/```.*?```/s', '', $edited));

                        $fragment = $dom->createDocumentFragment();

                        if (!@$fragment->appendXML($edited)) 
                        {
                            $tmp = new DOMDocument();
                            $tmp->loadHTML('<div>'.$edited.'</div>');
                            foreach ($tmp->documentElement->childNodes as $child) {
                                $fragment->appendChild($dom->importNode($child, true));
                            }
                        }

                        if ($selector === 'full_content') {
                            while ($body->firstChild) $body->removeChild($body->firstChild);
                            $body->appendChild($fragment);
                        } else {
                            $target_node->parentNode->replaceChild($fragment, $target_node);
                        }

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

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

                        if (is_wp_error($updated)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output' => "Error updating post.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => "Success: post updated",
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => 'Arguments missing',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'list_available_ai_agents') 
                {
                    $toolOutputs[] = [
                        'tool_call_id' => $zid, 
                        'output' => 'This tool is not supported',
                        'message' => $response['message']
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                    continue;
                }
                elseif ($function_name === 'delegate_to_ai_agent') 
                {
                    $toolOutputs[] = [
                        'tool_call_id' => $zid, 
                        'output' => 'This tool is not supported',
                        'message' => $response['message']
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                    continue;
                }
                elseif ($function_name === 'read_server_file') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['file_path']))
                        {
                            $file_path = $arguments['file_path'];

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

                            if (!$real_path || strpos($real_path, $base_dir) !== 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Access denied',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $ext = pathinfo($real_path, PATHINFO_EXTENSION);
                            if (!in_array($ext, array('txt', 'log', 'csv', 'json'))) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid file type',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if (!file_exists($real_path)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'File not found',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $content = substr(file_get_contents($real_path), 0, 5000);

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => $content,
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'file_path parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'write_server_file') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['filename']) && isset($arguments['content']))
                        {
                            $filename  = $arguments['filename'];
                            $content   = $arguments['content'];
                            $overwrite = isset($arguments['overwrite']) ? (bool)$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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid filename',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid file type',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            // 4. Size limit
                            if (strlen($content) > 2 * 1024 * 1024)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Content too large (max 2MB)',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid write path',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            // 6. Prevent overwrite
                            if (file_exists($target_path) && !$overwrite)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'File exists (overwrite not allowed)',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            // 7. JSON validation
                            if ($ext === 'json')
                            {
                                json_decode($content, true);
                                if (json_last_error() !== JSON_ERROR_NONE)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Invalid JSON content',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to write file',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'Success: File saved at /wp-content/uploads/aiomatic-exports/' . basename($target_path),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'filename or content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'get_wp_post_data') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['post_id']))
                        {
                            $post_id = $arguments['post_id'];

                            if (empty($post_id)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: No Post ID provided.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $post = get_post($post_id);
                            if (!$post) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => "Error: Post with ID $post_id not found.",
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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 ---";

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => aiomatic_substr($final_output, 0, 45000),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'post_id parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'process_and_transform_data') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['operation']) && isset($arguments['input']))
                        {
                            $operation = $arguments['operation'];
                            $input     = $arguments['input'];

                            if (empty($operation) || empty($input)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: operation and input are required.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $decoded = json_decode($input, true);

                            switch ($operation) 
                            {
                                case 'parse_json':

                                    if ($decoded === null) 
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: Invalid JSON.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                        continue 2;
                                    }

                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => json_encode($decoded),
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    break;

                                case 'stringify_json':

                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => json_encode($input),
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    break;

                                case 'list_keys':

                                    if (!is_array($decoded)) 
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: Input must be JSON object or array.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                        continue 2;
                                    }

                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => implode(', ', array_keys($decoded)),
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    break;

                                case 'extract_field':

                                    if(!isset($arguments['field']))
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: field parameter required.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                        continue 2;
                                    }

                                    $field = $arguments['field'];

                                    if (!is_array($decoded)) 
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: Input must be JSON.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                        continue 2;
                                    }

                                    if (isset($decoded[$field])) 
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => json_encode($decoded[$field]),
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                    }
                                    else
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: field not found.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                    }
                                    break;

                                case 'filter_equals':

                                    if(!isset($arguments['field']))
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: field parameter required.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                        continue 2;
                                    }

                                    $field = $arguments['field'];
                                    $value = isset($arguments['value']) ? $arguments['value'] : '';

                                    if (!is_array($decoded)) 
                                    {
                                        $toolOutputs[] = [
                                            'tool_call_id' => $zid, 
                                            'output' => 'Error: Input must be JSON array.',
                                            'message' => $response['message']
                                        ];
                                        do_action('aiomatic_tool_result', end($toolOutputs));
                                        continue 2;
                                    }

                                    $filtered = array();

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

                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => json_encode($filtered),
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    break;

                                default:

                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Error: Unknown operation.',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    break;
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'operation or input parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'pause_execution') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['seconds']))
                        {
                            $seconds = (int)$arguments['seconds'];

                            if ($seconds <= 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: seconds must be greater than 0.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            sleep($seconds);

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Waited $seconds seconds.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'seconds parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'wp_validate_post_state') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['post_id']) && isset($arguments['checks']))
                        {
                            $post_id = $arguments['post_id'];
                            $checks  = $arguments['checks'];

                            if (empty($post_id)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: post_id is required.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if (!is_array($checks) || empty($checks)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: checks must be a non-empty array.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => implode("\n", $results),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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($arguments['min_content_length']) ? (int)$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 = $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 = $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);

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => $output,
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'post_id or checks parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'wp_taxonomy_discovery') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['operation']))
                        {
                            $operation = $arguments['operation'];

                            if (empty($operation)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: operation parameter was not provided.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            if (!in_array($operation, array('list_taxonomies','list_terms','get_post_terms','create_term','set_post_terms'), true))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: Invalid operation parameter provided.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                                if (empty($taxonomies))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'No taxonomies found on this site.',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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);

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => aiomatic_substr($output, 0, 45000),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }

                            // LIST TERMS
                            elseif ($operation === 'list_terms')
                            {
                                if(!isset($arguments['taxonomy']))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'taxonomy parameter was not provided',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = $arguments['taxonomy'];

                                if (!taxonomy_exists($taxonomy))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => "Error: Taxonomy $taxonomy does not exist.",
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                if (is_wp_error($terms) || empty($terms))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => "No terms found for taxonomy: $taxonomy",
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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);

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => aiomatic_substr($output, 0, 45000),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }

                            // GET POST TERMS
                            elseif ($operation === 'get_post_terms')
                            {
                                if(!isset($arguments['taxonomy']) || !isset($arguments['post_id']))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'taxonomy or post_id parameter missing',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = $arguments['taxonomy'];
                                $post_id  = $arguments['post_id'];

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

                                if (empty($terms) || is_wp_error($terms))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => "No terms assigned.",
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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);

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $output,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }

                            // CREATE TERM
                            elseif ($operation === 'create_term')
                            {
                                if(!isset($arguments['taxonomy']) || !isset($arguments['term_name']))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'taxonomy or term_name missing',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = $arguments['taxonomy'];
                                $term_name = $arguments['term_name'];

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

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

                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => "Term already exists. ID: $term_id",
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                if (is_wp_error($created))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => $created->get_error_message(),
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => "Created term ID: " . $created['term_id'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            elseif ($operation === 'set_post_terms')
                            {
                                if (
                                    !isset($arguments['taxonomy']) ||
                                    !isset($arguments['post_id']) ||
                                    !isset($arguments['term_name'])
                                )
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'taxonomy, post_id or term_name missing',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                $taxonomy = sanitize_text_field($arguments['taxonomy']);
                                $post_id  = intval($arguments['post_id']);
                                $terms    = sanitize_text_field($arguments['term_name']);

                                if (empty($taxonomy) || $post_id <= 0 || empty($terms))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Invalid taxonomy, post_id or term_name',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

                                if (!taxonomy_exists($taxonomy))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => "Taxonomy $taxonomy does not exist",
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'No valid terms to assign',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => "Success: Assigned " . count($term_ids) . " terms to post $post_id",
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'operation parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'get_environment_info') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['info_type']))
                        {
                            $type = sanitize_text_field($arguments['info_type']);

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

                            if (!in_array($type, $allowed, true)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: Invalid info_type parameter.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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";
                            }

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => aiomatic_substr(trim($output), 0, 45000),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'info_type parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'manage_wp_post') 
                {
                    if (empty($arguments)) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    if (!isset($arguments['operation']))
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => 'operation parameter was not provided',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    $operation = sanitize_text_field($arguments['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))
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => 'Error: Invalid operation. Allowed operations are: ' . implode(', ', $allowed_operations),
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    // --- CREATE ---
                    if ($operation === 'create')
                    {
                        if (empty($arguments['post_title']) || empty($arguments['post_content']))
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output' => 'Error: Both post_title and post_content are required.',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

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

                        $new_post_id = wp_insert_post($post_data, true);

                        if (is_wp_error($new_post_id)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid,
                                'output' => 'Error: ' . $new_post_id->get_error_message(),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

                        if (!empty($arguments['featured_image_id']))
                        {
                            set_post_thumbnail($new_post_id, intval($arguments['featured_image_id']));
                        }

                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => "Success: Post created. ID: $new_post_id. URL: " . get_permalink($new_post_id),
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }

                    // --- IDS ---
                    $post_ids = [];

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

                    if (empty($post_ids))
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid,
                            'output' => 'Error: ID or post_ids parameter is required.',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        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;
                        }

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

                            foreach (['post_title','post_content','post_status','post_type','post_excerpt'] as $f)
                            {
                                if (isset($arguments[$f]))
                                {
                                    $post_data[$f] = ($f === 'post_title') ? wp_strip_all_tags($arguments[$f]) : $arguments[$f];
                                }
                            }

                            if (isset($arguments['post_name'])) $post_data['post_name'] = sanitize_title($arguments['post_name']);
                            if (isset($arguments['post_parent'])) $post_data['post_parent'] = intval($arguments['post_parent']);
                            if (isset($arguments['menu_order'])) $post_data['menu_order'] = intval($arguments['menu_order']);
                            if (isset($arguments['comment_status'])) $post_data['comment_status'] = $arguments['comment_status'];
                            if (isset($arguments['ping_status'])) $post_data['ping_status'] = $arguments['ping_status'];

                            $updated = wp_update_post($post_data, true);

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

                            if (isset($arguments['featured_image_id']))
                            {
                                $fid = intval($arguments['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($arguments['featured_image_id'] ?? 0);
                            $image_url = isset($arguments['image_url']) ? trim($arguments['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";
                        }

                        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' || $operation === 'prepend_content')
                        {
                            if (empty($arguments['post_content']))
                            {
                                $results[] = "Error: post_content required $post_id";
                                continue;
                            }

                            $content = $operation === 'append_content'
                                ? $existing_post->post_content . $arguments['post_content']
                                : $arguments['post_content'] . $existing_post->post_content;

                            wp_update_post(['ID' => $post_id, 'post_content' => $content]);

                            $results[] = "Content updated $post_id";
                        }

                        elseif ($operation === 'set_meta')
                        {
                            if (empty($arguments['meta_key']))
                            {
                                $results[] = "Error meta_key $post_id";
                                continue;
                            }

                            update_post_meta($post_id, sanitize_key($arguments['meta_key']), $arguments['meta_value'] ?? '');
                            $results[] = "Meta set $post_id";
                        }

                        elseif ($operation === 'delete_meta')
                        {
                            if (empty($arguments['meta_key']))
                            {
                                $results[] = "Error meta_key $post_id";
                                continue;
                            }

                            delete_post_meta($post_id, sanitize_key($arguments['meta_key']));
                            $results[] = "Meta deleted $post_id";
                        }

                        elseif ($operation === 'set_terms')
                        {
                            $taxonomy = sanitize_key($arguments['taxonomy'] ?? '');
                            $terms = array_map('intval', array_filter(array_map('trim', explode(',', $arguments['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";
                        }
                    }

                    $toolOutputs[] = [
                        'tool_call_id' => $zid,
                        'output' => implode("\n", $results),
                        'message' => $response['message']
                    ];
                    do_action('aiomatic_tool_result', end($toolOutputs));
                }
                elseif ($function_name === 'search_site_posts') 
                {
                    if (!empty($arguments)) 
                    {
                        $query_str   = isset($arguments['query']) ? $arguments['query'] : '';
                        $post_type   = !empty($arguments['post_type']) ? (array)$arguments['post_type'] : array('post','page');
                        $post_status = !empty($arguments['post_status']) ? sanitize_text_field($arguments['post_status']) : 'any';
                        $limit       = !empty($arguments['posts_per_page']) ? min((int)$arguments['posts_per_page'], 20) : 5;
                        $offset      = !empty($arguments['offset']) ? max((int)$arguments['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($arguments['orderby'])) {
                            $args['orderby'] = sanitize_text_field($arguments['orderby']);
                        }
                        if (!empty($arguments['order'])) {
                            $args['order'] = strtoupper($arguments['order']) === 'ASC' ? 'ASC' : 'DESC';
                        }
                        if (!empty($arguments['meta_key'])) {
                            $args['meta_key'] = sanitize_text_field($arguments['meta_key']);
                        }

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

                        // date (FIXED)
                        if (!empty($arguments['date_after']) || !empty($arguments['date_before'])) 
                        {
                            $date_query = array();

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

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

                        // taxonomy
                        if (!empty($arguments['taxonomy']) && !empty($arguments['terms'])) 
                        {
                            $terms = array_map('intval', explode(',', $arguments['terms']));

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

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

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

                        if (!empty($arguments['meta_filters']) && is_string($arguments['meta_filters'])) 
                        {
                            $allowed_compares = ['=', '!=', '>', '>=', '<', '<=', 'LIKE', 'EXISTS', 'NOT EXISTS'];
                            $filters = explode('|', $arguments['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] ?? '=');

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

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

                                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++;
                            }
                        }

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

                        if (isset($arguments['has_excerpt'])) {
                            if ($arguments['has_excerpt'] === 'yes') {
                                $has_excerpt_filter = 'yes';
                            } elseif ($arguments['has_excerpt'] === 'no') {
                                $has_excerpt_filter = 'no';
                            }
                        }

                        $length_filter_cb = null;

                        $min_len = isset($arguments['min_content_length']) ? (int)$arguments['min_content_length'] : 0;
                        $max_len = isset($arguments['max_content_length']) && (int)$arguments['max_content_length'] > 0
                            ? (int)$arguments['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)) 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "No results found for the given filters.",
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            continue;
                        }

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

                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => aiomatic_substr($output, 0, 30000),
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'wp_sideload_media') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['image_url']))
                        {
                            $image_url = $arguments['image_url'];
                            $post_id = 0;
                            if(isset($arguments['post_id']))
                            {
                                $post_id = $arguments['post_id'];
                            }

                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: No image URL provided.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $result->get_error_message(),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => "Attachment ID: $result | URL: " . wp_get_attachment_url($result),
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'image_url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'get_post_structure') 
                {
                    if (!empty($arguments)) 
                    {
                        if(isset($arguments['post_id']))
                        {
                            $post_id = intval($arguments['post_id']);

                            if ($post_id <= 0) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: post_id is required.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $post = get_post($post_id);

                            if (!$post) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Post not found.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

                            $content = $post->post_content;

                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: Empty content.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }

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

                            if (empty($html)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: Failed to normalize content.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error: Failed parsing HTML.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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
                            ]);

                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => $result,
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'post_id parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode get_post_structure arguments: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'get_wp_media_info') 
                {
                    if (!empty($arguments)) 
                    {
                        if (isset($arguments['post_id']) || isset($arguments['attachment_id']))
                        {
                            $post_id       = isset($arguments['post_id']) ? intval($arguments['post_id']) : 0;
                            $attachment_id = isset($arguments['attachment_id']) ? intval($arguments['attachment_id']) : 0;
                            $include_att   = isset($arguments['include_attachments']) ? (bool)$arguments['include_attachments'] : false;

                            $output = array();

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

                                if (!$attachment || $attachment->post_type !== 'attachment')
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Error: Attachment not found.',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    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']}";
                                }

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => implode("\n", $output),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if ($post_id > 0)
                            {
                                $post = get_post($post_id);

                                if (!$post)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Error: Post not found.',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }

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

                                $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";
                                }

                                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";
                                    }
                                }

                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => implode("\n", $output),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'post_id or attachment_id parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($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) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Required plugin (Aimogen Extension Toubiz API) not activated.',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }
                    if (!function_exists('aiomatic_get_toubiz_api_results')) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Required plugin (Aimogen Extension Toubiz API) not correctly installed.',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        continue;
                    }
                    $search = '';
                    if(isset($arguments['search']))
                    {
                        $search = $arguments['search'];
                    }
                    $date_after = '';
                    if(isset($arguments['date_after']))
                    {
                        $date_after = $arguments['date_after'];
                    }
                    $date_before = '';
                    if(isset($arguments['date_before']))
                    {
                        $date_before = $arguments['date_before'];
                    }
                    $type = '';
                    if(isset($arguments['type']))
                    {
                        $type = $arguments['type'];
                    }
                    $event_type = '';
                    if(isset($arguments['event_type']))
                    {
                        $event_type = $arguments['event_type'];
                    }
                    $rectangle_area = '';
                    if(isset($arguments['rectangle_area']))
                    {
                        $rectangle_area = $arguments['rectangle_area'];
                    }
                    $distance_from = '';
                    if(isset($arguments['distance_from']))
                    {
                        $distance_from = $arguments['distance_from'];
                    }
                    $languages = '';
                    if(isset($arguments['languages']))
                    {
                        $languages = $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) 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Failed to access Toubiz API',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                        aiomatic_log_to_file('Failed to access Toubiz API: ' . print_r($arguments, true));
                    } 
                    else 
                    {
                        $toubiz_data = aiomatic_substr($toubiz_data, 0, 400000);
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => $toubiz_data,
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'website_scraper') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['url'])) 
                        {
                            $scurl = $arguments['url'];
                            if (empty($scurl) || !filter_var($scurl, FILTER_VALIDATE_URL)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid scrape url provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $parsed = parse_url($scurl);
                            if (!isset($parsed['scheme']) || !in_array(strtolower($parsed['scheme']), ['http', 'https']))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Only http/https URLs are allowed',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)
                            ) {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Access to local/internal URLs is not allowed',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $scrape_method = $aiomatic_Chatbot_Settings['scrape_method'] ?? '0';
                            $max_chars = $aiomatic_Chatbot_Settings['max_chars'] ?? '';
                            $scrape_selector = 'auto';
                            $scrape_string = '';
                            $strip_tags = ($aiomatic_Chatbot_Settings['strip_tags'] ?? '') === 'on' ? '1' : '0';
                
                            $scraped_data = aiomatic_scrape_page($scurl, $scrape_method, $scrape_selector, $scrape_string);
                            
                            if ($scraped_data === false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to scrape website URL: ' . $scurl,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to scrape website: ' . print_r($arguments, true));
                            } 
                            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);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $scraped_data,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'rss_feed_parser') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['url'])) 
                        {
                            $scurl = $arguments['url'];
                            if (empty($scurl)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty RSS feed URL provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $max_rss_items = isset($aiomatic_Chatbot_Settings['max_rss_items']) ? intval(trim($aiomatic_Chatbot_Settings['max_rss_items'])) : PHP_INT_MAX;
                            $rss_template = $aiomatic_Chatbot_Settings['rss_template'] ?? '[%%item_counter%%]: %%item_title%% - %%item_description%%';
                
                            // Load the RSS parser library
                            try 
                            {
                                if (!class_exists('SimplePie_Autoloader', false)) 
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            } 
                            catch (Exception $e) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to load RSS parser library',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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()) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error in parsing RSS feed: ' . $feed->error(),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $final_result = '';
                            $items = $feed->get_items();
                            $rss_feeds = [];
                            foreach ($items as $itemx) 
                            {
                                $post_link = trim($itemx->get_permalink());
                                $user_name = ($fauthor = $itemx->get_author()) ? $fauthor->get_name() : '';
                                $feed_cats = array_map(function($xcategory){ return $xcategory->get_label(); }, $itemx->get_categories());
                                $post_cats = implode(',', $feed_cats);
                                $post_excerpt = $itemx->get_description();
                                $final_content = $itemx->get_content();
                                $rss_feeds[$itemx->get_title()] = [
                                    '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 ($final_result === '') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse RSS URL (no data returned): ' . $scurl,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to parse RSS feed: ' . print_r($arguments, true));
                            } 
                            else 
                            {
                                $final_result = aiomatic_substr($final_result, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $final_result,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'google_results_parser') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['keywords'])) 
                        {
                            $keywords = $arguments['keywords'];
                            if (empty($keywords)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty keywords parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $max_google_items = isset($aiomatic_Chatbot_Settings['max_google_items']) ? intval(trim($aiomatic_Chatbot_Settings['max_google_items'])) : PHP_INT_MAX;
                            $google_template = $aiomatic_Chatbot_Settings['google_template'] ?? '[%%item_counter%%]: %%item_title%% - %%item_snippet%%';
                
                            $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 ($final_res === '') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Google SERP for keyword (no data returned): ' . $keywords,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to parse Google SERP: ' . print_r($arguments, true));
                            } 
                            else 
                            {
                                $final_res = aiomatic_substr($final_res, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $final_res,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'keywords parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'generate_ai_model_reasoning')
                {
                    if (isset($arguments)) 
                    {
                        $result = '';
                        if(isset($arguments['prompt']))
                        {
                            $prompt = $arguments['prompt'];
                            if (empty($prompt)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty prompt parameter provided'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $model = '';
                            if(isset($arguments['model']))
                            {
                                $model = $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))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => '[ERROR] API key not configured in plugin settings.'
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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 = '';
                            $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(), '', '', '');
                            if($generated_text === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => '[ERROR] Failed to generate content using AI writer: ' . $model . ' - error: ' . $aierror
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            else
                            {
                                $new_post_content = aiomatic_sanitize_ai_result($generated_text);
                                if(empty($new_post_content))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => '[ERROR] No content returned by the AI writer!'
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                                else
                                {
                                    $new_post_content = aiomatic_substr($new_post_content, 0, 400000);
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => $new_post_content
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'prompt parameter was not provided'
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($arguments, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call'
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'query_wp_database')
                {
                    if (isset($arguments)) 
                    {
                        $result = '';
                        if(isset($arguments['query']))
                        {
                            $query = $arguments['query'];
                            if (empty($query)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty query parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => "Query type '$query_type' is not allowed. Allowed types: " . implode(', ', $allowed_commands),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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) 
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Error! Invalid query or no results found.',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                } 
                                else 
                                {
                                    if ($query_type === 'SELECT' && count($lead_result) > 500) {
                                        $lead_result = array_slice($lead_result, 0, 500);
                                    }
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => json_encode($lead_result),
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                            } 
                            catch (Exception $e) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error executing the query: ' . $e->getMessage(),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'query parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode assistant function calling: ' . print_r($arguments, true));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'aimogen_execute_omniblock_rule') 
                {
                    if(isset($arguments))
                    {
                        $result = '';
                        if(isset($arguments['omniblock_id']))
                        {
                            if(isset($arguments['input_parameters']))
                            {
                                $input_text = $arguments['input_parameters'];
                            }
                            else
                            {
                                $input_text = '';
                            }
                            $omniblock_id = $arguments['omniblock_id'];
                            if (empty($omniblock_id)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty omniblock_id parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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))
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'This OmniBlock ID does not exist in the configured rules',
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                    continue;
                                }
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No OmniBlock rules configured in settings',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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]))
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Incorrect OmniBlock ID submitted in request',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            if(count($id_parts) > 2)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Incorrect format for OmniBlock IDs',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                            $param = $id_parts[0];
                            $omniTriggerID = $id_parts[1];
                            $rules = get_option('aiomatic_omni_list', array());
                            $found = false;
                            if (!empty($rules)) 
                            {
                                $default_block_types = aiomatic_omniblocks_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);
                                                    }
                                                    $toolOutputs[] = [
                                                        'tool_call_id' => $zid, 
                                                        'output' => wp_kses_post($return_me),
                                                        'message' => $response['message']
                                                    ];
                                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                                    $found = true;
                                                    break 2;
                                                }
                                            }
                                        }
                                    }
                                    $cont = $cont + 1;
                                }
                                if($found == false)
                                {
                                    $toolOutputs[] = [
                                        'tool_call_id' => $zid, 
                                        'output' => 'Specified \'AI Chatbot Trigger\' OmniBlock ID not found (2): ' . $omniblock_id,
                                        'message' => $response['message']
                                    ];
                                    do_action('aiomatic_tool_result', end($toolOutputs));
                                }
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No rules found for aiomatic_omni_list!',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            continue;
                        }
                        else
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'omniblock_id argument not set for the function call',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                        }
                    }
                    else
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'lead_capture') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['email'])) 
                        {
                            $raw_img_list = array();
                            $full_result_list = array();
                            $name = '';
                            $phone_number = '';
                            $job_title = '';
                            $company_name = '';
                            $location = '';
                            $birth_date = '';
                            $how_you_found_us = '';
                            $website_url = '';
                            $preferred_contact_method = '';
                            $email = $arguments['email'];
                            if (empty($email)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty email parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if(isset($arguments['name']))
                            {
                                $name = $arguments['name'];
                            }
                            if(isset($arguments['phone_number']))
                            {
                                $phone_number = $arguments['phone_number'];
                            }
                            if(isset($arguments['job_title']))
                            {
                                $job_title = $arguments['job_title'];
                            }
                            if(isset($arguments['company_name']))
                            {
                                $company_name = $arguments['company_name'];
                            }
                            if(isset($arguments['location']))
                            {
                                $location = $arguments['location'];
                            }
                            if(isset($arguments['birth_date']))
                            {
                                $birth_date = $arguments['birth_date'];
                            }
                            if(isset($arguments['how_you_found_us']))
                            {
                                $how_you_found_us = $arguments['how_you_found_us'];
                            }
                            if(isset($arguments['website_url']))
                            {
                                $website_url = $arguments['website_url'];
                            }
                            if(isset($arguments['preferred_contact_method']))
                            {
                                $preferred_contact_method = $arguments['preferred_contact_method'];
                            }
                            $lead_result = aiomatic_save_lead_data(
                                $email,
                                $name,
                                $phone_number,
                                $job_title,
                                $company_name,
                                $location,
                                $birth_date,
                                $how_you_found_us,
                                $website_url,
                                $preferred_contact_method
                            );
                            if($lead_result === false)
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Error! Failed to save the lead data.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                            else
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Lead data saved successfully.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'email parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Lead capture function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'royalty_free_image_search') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['keyword'])) 
                        {
                            $keyword = $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)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty keyword parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $raw_img_list = [];
                            $full_result_list = [];
                            $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, [], $full_result_list);
                
                            if ($temp_get_img === false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to get royalty free image for keyword: ' . $keyword,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to get royalty free image: ' . print_r($arguments, true));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => '<img class="image_max_w_ai" src="' . aiomatic_sanitize_image_src($temp_get_img) . '">',
                                    'output' => $temp_get_img,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'keyword parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'youtube_video_captions') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['url'])) 
                        {
                            $zurl = $arguments['url'];
                            $zurl = aiomatic_extractYouTubeVideoId($zurl);
                            if (empty($zurl)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty url parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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'];
                            }
                
                            // Process the returned captions
                            if (empty($returned_caption)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to find subtitles for video URL: ' . $zurl,
                                    'message' => $response['message']
                                ];
                            } 
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            if (empty($returned_caption)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse YouTube video caption for URL (no data returned): ' . $zurl,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode YouTube captions: ' . print_r($arguments, true));
                            } 
                            else 
                            {
                                $returned_caption = aiomatic_substr($returned_caption, 0, 400000);
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => $returned_caption,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'youtube_video_search') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['keyword'])) 
                        {
                            $keyword = $arguments['keyword'];
                            if (empty($keyword)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty keyword parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $new_vid = aiomatic_get_video($keyword, '', array());
                            if ($new_vid == '') 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse YouTube video search results for keyword (no data returned): ' . $keyword,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                aiomatic_log_to_file('Failed to decode YouTube search: ' . print_r($arguments, true));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'echo' => $new_vid,
                                    'output' => $new_vid,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'keyword parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_facebook_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $fbomatic_active = is_plugin_active('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php');
                            if (!$fbomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (F-omatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $furl = $arguments['url'] ?? '';
                            $zcontent = $arguments['content'];
                            if (empty($zcontent)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $page_to_post = $aiomatic_Chatbot_Settings['facebook_post_select'] ?? '';
                
                            if (empty($page_to_post)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No page where to publish the post was selected',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Facebook posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Facebook posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Facebook posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_facebook_image') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['image_url'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $fbomatic_active = is_plugin_active('fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php');
                            if (!$fbomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (F-omatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $caption = $arguments['caption'] ?? '';
                            $image_url = $arguments['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty image_url parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $page_to_post = $aiomatic_Chatbot_Settings['facebook_post_select'] ?? '';
                
                            if (empty($page_to_post)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No page where to publish the post was selected',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'fbomatic-facebook-post-generator/fbomatic-facebook-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Facebook image posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Facebook image posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Facebook image posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'image_url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'publish_twitter_x_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $twitomatic_active = is_plugin_active('twitomatic-twitter-post-generator/twitomatic-twitter-post-generator.php');
                            if (!$twitomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Twitomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $image_url = $arguments['image_url'] ?? '';
                            $zcontent = $arguments['content'];
                            if (empty($zcontent)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'twitomatic-twitter-post-generator/twitomatic-twitter-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Twitter posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Twitter posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Twitter posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_threads_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $threadsomatic_active = is_plugin_active('threadsomatic-threads-auto-poster/threadsomatic-threads-auto-poster.php');
                            if (!$threadsomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Threadsomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $image_url = $arguments['image_url'] ?? '';
                            $zcontent = $arguments['content'];
                            if (empty($zcontent)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'threadsomatic-threads-auto-poster/threadsomatic-threads-auto-poster.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Threads posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Threads posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Threads posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_instagram_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['image_url'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $instamatic_active = is_plugin_active('instamatic-instagram-post-generator/instamatic-instagram-post-generator.php');
                            if (!$instamatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Instamatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $zcontent = $arguments['content'] ?? '';
                            $image_url = $arguments['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty image_url parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'instamatic-instagram-post-generator/instamatic-instagram-post-generator.php' => [
                                        'iMediamatic Automatic Post Generator', 
                                        'https://1.envato.market/instamatic'
                                    ]
                                ]
                            ];
                            $return_me = aiomatic_post_image_to_instagram($card_type_found, $zcontent, $image_url);
                
                            if (isset($return_me['error'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Instagram posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Instagram posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Instagram posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'image_url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_pinterest_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['image_url'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $pinterestomatic_active = is_plugin_active('pinterestomatic-pinterest-post-generator/pinterestomatic-pinterest-post-generator.php');
                            if (!$pinterestomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Pinterestomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $page_to_post = $aiomatic_Chatbot_Settings['pinterest_post_select'] ?? '';
                
                            if (empty($page_to_post)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No boards where to publish the post were selected',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $description = $arguments['description'] ?? '';
                            $title = $arguments['title'] ?? '';
                            $pin_url = $arguments['pin_url'] ?? '';
                            $image_url = $arguments['image_url'];
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty image_url parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'pinterestomatic-pinterest-post-generator/pinterestomatic-pinterest-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Pinterest posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Pinterest posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Pinterest posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'image_url parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'publish_google_my_business_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['image_url']) && isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $businessomatic_active = is_plugin_active('businessomatic-google-my-business-post-generator/businessomatic-google-my-business-post-generator.php');
                            if (!$businessomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Businessomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $page_to_post = $aiomatic_Chatbot_Settings['business_post_select'] ?? '';
                
                            if (empty($page_to_post)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No pages where to publish the post was selected',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $content = $arguments['content'];
                            $image_url = $arguments['image_url'];
                
                            if (empty($image_url)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty image_url parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'businessomatic-google-my-business-post-generator/businessomatic-google-my-business-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'GMB posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse GMB posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'GMB posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'image_url or content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_youtube_community_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['post_type']) && isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $youtubomatic_active = is_plugin_active('youtubomatic-youtube-post-generator/youtubomatic-youtube-post-generator.php');
                            if (!$youtubomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Youtubomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $content = $arguments['content'];
                            $post_type = trim($arguments['post_type']);
                
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if (empty($post_type) || !in_array($post_type, ['image', 'text'])) 
                            {
                                $post_type = 'text';
                            }
                
                            $image_url = $arguments['image_url'] ?? '';
                            $media = $image_url ? [$image_url] : [];
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'youtubomatic-youtube-post-generator/youtubomatic-youtube-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'YouTube Community posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse YouTube Community posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'YouTube Community posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'post_type or content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'publish_reddit_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['title']) && isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $redditomatic_active = is_plugin_active('redditomatic-reddit-post-generator/redditomatic-reddit-post-generator.php');
                            if (!$redditomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Redditomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $content = $arguments['content'];
                            $title = $arguments['title'];
                
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if (empty($title)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty title parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $subreddit_to_post = $aiomatic_Chatbot_Settings['subreddits_list'] ?? '';
                
                            if (empty($subreddit_to_post)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No subreddits were defined where to publish the post',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'redditomatic-reddit-post-generator/redditomatic-reddit-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Reddit posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse Reddit posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Reddit posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'title or content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'publish_linkedin_post') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['title']) && isset($arguments['content'])) 
                        {
                            if (!function_exists('is_plugin_active')) 
                            {
                                include_once(ABSPATH . 'wp-admin/includes/plugin.php');
                            }
                
                            $linkedinomatic_active = is_plugin_active('linkedinomatic-linkedin-post-generator/linkedinomatic-linkedin-post-generator.php');
                            if (!$linkedinomatic_active) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Required plugin (Linkedinomatic) not activated.',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $content = $arguments['content'];
                            $title = $arguments['title'];
                
                            if (empty($content)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty content parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if (empty($title)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty title parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $description = $arguments['description'] ?? '';
                            $post_link = $arguments['link'] ?? '';
                            $image_url = $arguments['image_url'] ?? '';
                
                            $aiomatic_Chatbot_Settings = get_option('aiomatic_Chatbot_Settings', false);
                            $selected_pages = $aiomatic_Chatbot_Settings['linkedin_selected_pages'] ?? '';
                
                            if (empty($selected_pages)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'No pages selected where to post to LinkedIn',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $card_type_found = [
                                'required_plugin' => [
                                    'linkedinomatic-linkedin-post-generator/linkedinomatic-linkedin-post-generator.php' => [
                                        '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'])) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'LinkedIn posting failed: ' . $return_me['error'],
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            elseif (empty($return_me)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to parse LinkedIn posting results',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'LinkedIn posting successful: ' . json_encode($return_me, true),
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'title or content parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                } 
                elseif ($function_name === 'wp_send_email') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['subject']) && isset($arguments['content']) && isset($arguments['recipient_email'])) 
                        {
                            $subject = $arguments['subject'];
                            $content = $arguments['content'];
                            $recipient_email = $arguments['recipient_email'];
                
                            if (empty($subject) || empty($content) || empty($recipient_email)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty subject, content or recipient_email parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $admin_mail = get_option('admin_email');
                            $headers = [
                                'From: Aimogen Plugin Chatbot <' . $admin_mail  . '>',
                                'Reply-To: ' . $admin_mail,
                                'X-Mailer: PHP/' . phpversion(),
                                'Content-Type: text/html',
                                'Charset: ' . get_option('blog_charset', 'UTF-8')
                            ];
                
                            $sent = wp_mail($recipient_email, $subject, $content, $headers);
                
                            if ($sent === false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to send email to address: ' . $recipient_email,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'OK',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'subject, content or recipient_email parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }
                elseif ($function_name === 'call_webhook') 
                {
                    if (!empty($arguments)) 
                    {
                        $result = '';
                        if (isset($arguments['webhook_url']) && isset($arguments['method_selector'])) 
                        {
                            $webhook_url = $arguments['webhook_url'];
                            $method_selector = strtoupper($arguments['method_selector']); // Make sure the method is in uppercase
                
                            if (empty($webhook_url) || empty($method_selector)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Empty webhook_url or method_selector parameter provided',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $content_type = $arguments['content_type'] ?? '';
                            $post_template = $arguments['data'] ?? '';
                            $headers_template = $arguments['headers'] ?? '';
                
                            $urlParsed = wp_parse_url($webhook_url, PHP_URL_HOST);
                            if (filter_var($webhook_url, FILTER_VALIDATE_URL) === false || empty($urlParsed)) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Invalid webhook_url entered: ' . $webhook_url,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            } 
                            elseif ($content_type == 'JSON' && json_decode($post_template, true) === null) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'The JSON data must be valid: ' . $webhook_url,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                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)) && strpos($arr_fr, '=>') !== false) 
                                    {
                                        list($key, $value) = explode('=>', $arr_fr, 2);
                                        $headers[] = trim($key) . ': ' . trim($value);
                                    }
                                }
                            }
                
                            $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)) && strpos($arr_fr, '=>') !== false) 
                                    {
                                        list($key, $value) = explode('=>', $arr_fr, 2);
                                        $content_params[trim($key)] = trim($value);
                                    }
                                }
                            }
                
                            $ch = curl_init();
                            if ($ch === false) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to initialize curl in webhook execution',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable') 
                            {
                                $proxy_list = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                $random_proxy = trim($proxy_list[array_rand($proxy_list)]);
                                curl_setopt($ch, CURLOPT_PROXY, $random_proxy);
                                
                                if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                {
                                    $proxy_auth_list = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                    $random_auth = trim($proxy_auth_list[array_rand($proxy_auth_list)]);
                                    if (!empty($random_auth)) 
                                    {
                                        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $random_auth);
                                    }
                                }
                            }
                
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                
                            if (in_array($method_selector, ['POST', 'PUT', 'DELETE'])) 
                            {
                                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method_selector);
                                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($content_params));
                                    $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) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Failed to send webhook request to ' . $webhook_url,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            $err = curl_error($ch);
                            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);
                
                            if ($err) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Webhook request error to URL ' . $webhook_url . ' - error: ' . $err,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                                continue;
                            }
                
                            if ($statusCode >= 200 && $statusCode < 300) 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Webhook URL called successfully!',
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            } 
                            else 
                            {
                                $toolOutputs[] = [
                                    'tool_call_id' => $zid, 
                                    'output' => 'Webhook unexpected return code to URL ' . $webhook_url . ' - return code: ' . $statusCode,
                                    'message' => $response['message']
                                ];
                                do_action('aiomatic_tool_result', end($toolOutputs));
                            }
                        } 
                        else 
                        {
                            $toolOutputs[] = [
                                'tool_call_id' => $zid, 
                                'output' => 'webhook_url or method_selector parameter was not provided',
                                'message' => $response['message']
                            ];
                            do_action('aiomatic_tool_result', end($toolOutputs));
                            aiomatic_log_to_file('Failed to decode Ollama function calling: ' . print_r($arguments, true));
                        }
                    } 
                    else 
                    {
                        $toolOutputs[] = [
                            'tool_call_id' => $zid, 
                            'output' => 'Arguments not set for the function call',
                            'message' => $response['message']
                        ];
                        do_action('aiomatic_tool_result', end($toolOutputs));
                    }
                }                            
            }
        }
    }
    return $toolOutputs;
}
?>
