<?php

defined('ABSPATH') or die();
add_action('add_meta_boxes', function () {
    add_meta_box(
        'aiomatic_agent_task_runner',
        esc_html__('Run Task', 'aiomatic-automatic-ai-content-writer'),
        function($post){

            $status = get_post_status($post->ID);

            if ($status !== 'publish') {
                echo '<p>' . esc_html__('This agent must be published before you can run tasks.', 'aiomatic-automatic-ai-content-writer') . '</p>';
                return;
            }

            $agent_status = get_post_meta($post->ID, '_agent_status', true) ?: 'idle';

            echo '<a href="#" 
                class="button button-primary aiomatic-open-task-modal"
                data-agent-id="' . esc_attr($post->ID) . '"
                data-agent-status="' . esc_attr($agent_status) . '">
                ' . esc_html__('Run Task', 'aiomatic-automatic-ai-content-writer') . '
            </a>';
        },
        'aiomatic_agent',
        'side',
        'high'
    );
});
add_action('admin_footer', function () {

    $screen = get_current_screen();

    if (!$screen || $screen->post_type !== 'aiomatic_agent') {
        return;
    }

    if (!in_array($screen->base, ['post', 'post-new'])) {
        return;
    }
    ?>

    <div id="aiomatic-task-modal" class="aiomatic-modal">
        <div class="aiomatic-modal-content aiomatic-task-modal">
            <input type="hidden" id="aiomatic_task_agent_id">
            <input type="hidden" id="aiomatic_task_agent_status" value="idle">
            <input type="hidden" id="aiomatic_task_stop_url" value="">
            <span class="aiomatic-modal-close">&times;</span>

            <h2><?php echo esc_html__('Start Agent Task', 'aiomatic-automatic-ai-content-writer'); ?></h2>
                <div class="aiomatic-field">
                    <div class="aiomatic-goal-row">
                        <label><?php echo esc_html__('Goal (be as descriptive as possible) *', 'aiomatic-automatic-ai-content-writer'); ?></label>
                        <button type="button" id="aiomatic_refine_goal" class="button aiomatic-refine-btn">
                            ✨ <?php echo esc_html__('Refine with AI', 'aiomatic-automatic-ai-content-writer'); ?>
                        </button>
                    </div>
                    <textarea id="aiomatic_task_goal" placeholder="<?php echo esc_html__('What should the agent achieve?', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>
                </div>
                <div class="aiomatic-toggle-wrapper">
                    <button type="button" id="aiomatic_toggle_advanced" class="aiomatic-toggle-btn">
                        <span><?php echo esc_html__('Advanced Options', 'aiomatic-automatic-ai-content-writer'); ?></span>
                        <span class="aiomatic-icon">▼</span>
                    </button>
                </div>
                <div id="aiomatic_advanced_fields" class="aiomatic-extra-fields" style="display: none;">
                    <div class="aiomatic-field">
                        <label><?php echo esc_html__('Input / Context', 'aiomatic-automatic-ai-content-writer'); ?></label>
                        <textarea id="aiomatic_task_input" placeholder="<?php echo esc_html__('Optional context, keywords, URLs, data...', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>
                    </div>

                    <div class="aiomatic-field">
                        <label><?php echo esc_html__('Constraints', 'aiomatic-automatic-ai-content-writer'); ?></label>
                        <textarea id="aiomatic_task_constraints" placeholder="<?php echo esc_html__('One rule per line. Example: Max 1000 words', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>
                    </div>

                    <div class="aiomatic-field">
                        <label><?php echo esc_html__('Output Format', 'aiomatic-automatic-ai-content-writer'); ?></label>
                        <input type="text" id="aiomatic_task_output" placeholder="<?php echo esc_html__('e.g. HTML article, JSON, bullet list', 'aiomatic-automatic-ai-content-writer'); ?>">
                    </div>
                </div>
                <div class="aiomatic-field">
                    <label><?php echo esc_html__('Execution', 'aiomatic-automatic-ai-content-writer'); ?></label>

                    <div class="aiomatic-schedule-row">
                        <label style="margin-right:15px;">
                            <input type="radio" name="aiomatic_schedule_type" value="now" checked>
                            <?php echo esc_html__('Run now', 'aiomatic-automatic-ai-content-writer'); ?>
                        </label>

                        <label>
                            <input type="radio" name="aiomatic_schedule_type" value="schedule">
                            <?php echo esc_html__('Schedule', 'aiomatic-automatic-ai-content-writer'); ?>
                        </label>
                    </div>

                    <div id="aiomatic_schedule_picker" style="display:none; margin-top:10px;">
                        <small>
                            <?php
                            $tz = wp_timezone_string();
                            echo esc_html__('Server time:', 'aiomatic-automatic-ai-content-writer'); ?>
                            <span id="aiomatic-server-time">
                                <?php echo esc_html( current_time('Y-m-d H:i:s') ); ?>
                            </span>
                            (<?php echo esc_html($tz ?: 'UTC'); ?>)
                        </small>
                        <input type="datetime-local" id="aiomatic_schedule_datetime">
                    </div>
                </div>
                <div class="aiomatic-modal-actions">
                    <button type="button" class="button button-primary" id="aiomatic_start_task_btn">
                        <?php echo esc_html__('Start Task', 'aiomatic-automatic-ai-content-writer'); ?>
                    </button>

                    <button type="button" class="button button-primary" id="aiomatic_stop_task_btn" style="display:none;">
                        <?php echo esc_html__('Stop Task', 'aiomatic-automatic-ai-content-writer'); ?>
                    </button>
                </div>
            <div class="aiomatic-result-wrapper">
                <div class="aiomatic-result-header">
                    <span><?php echo esc_html__('Task Output', 'aiomatic-automatic-ai-content-writer'); ?></span>
                    <button type="button" id="aiomatic_result_toggle" class="aiomatic-result-btn">
                        ⤢
                    </button>
                </div>
            <pre id="aiomatic_task_result"></pre>
        </div>
        </div>
    </div>
<div id="aiomatic-logs-modal" class="aiomatic-modal">
    <div class="aiomatic-modal-content aiomatic-logs-modal">

        <span class="aiomatic-modal-close">&times;</span>

        <div class="aiomatic-logs-header">
            <h2><?php echo esc_html__('Agent Logs', 'aiomatic-automatic-ai-content-writer'); ?></h2>

            <div class="aiomatic-logs-actions">
                <select id="aiomatic-log-type-filter">
                    <option value=""><?php echo esc_html__('All Types', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="model_prompt">model_prompt</option>
                    <option value="model_response">model_response</option>
                    <option value="model_error">model_error</option>
                    <option value="tool_call">tool_call</option>
                    <option value="tool_result">tool_result</option>
                    <option value="tool_error">tool_error</option>
                    <option value="final">final</option>
                    <option value="error">error</option>
                </select>

                <button id="aiomatic-delete-logs" class="button button-secondary">
                    <?php echo esc_html__('Delete Logs', 'aiomatic-automatic-ai-content-writer'); ?>
                </button>
            </div>
        </div>

        <input type="hidden" id="aiomatic_logs_agent_id">

        <div id="aiomatic_logs_list" class="the-css-class">
            <div id="aiomatic-load-older-wrapper" style="display:none; text-align:center; margin-bottom:10px;">
                <button id="aiomatic-load-older-logs" class="button">
                    <?php echo esc_html__('Load older logs', 'aiomatic-automatic-ai-content-writer'); ?>
                </button>
            </div>
            <div id="aiomatic_logs_container">
                <div class="aiomatic-logs-loading"><?php echo esc_html__('Loading...', 'aiomatic-automatic-ai-content-writer'); ?></div>
            </div>
        </div>

    </div>
</div>
    <?php
});
add_action('admin_enqueue_scripts', function($hook) {
    if (!in_array($hook, ['post.php', 'post-new.php'])) {
        return;
    }
    $screen = get_current_screen();
    if (!$screen || $screen->post_type !== 'aiomatic_agent') {
        return;
    }
    wp_enqueue_script('jquery');
    wp_register_script(
        'aiomatic-agent-admin-js',
        false, 
        ['jquery'],
        null,
        true
    );
    wp_enqueue_script('aiomatic-agent-admin-js');
    wp_add_inline_script('aiomatic-agent-admin-js', "
jQuery(document).ready(function($){
    function aiomaticSetTaskModalState(status, stopUrl) {
        status = status || 'idle';
        stopUrl = stopUrl || '';

        $('#aiomatic_task_agent_status').val(status);
        $('#aiomatic_task_stop_url').val(stopUrl);

        if (status === 'running') {
            $('#aiomatic-task-modal h2').text('" . esc_html__('Stop Agent Task', 'aiomatic-automatic-ai-content-writer') . "');
            $('#aiomatic_start_task_btn').hide();

            $('#aiomatic_stop_task_btn').show();

            $('#aiomatic_task_goal, #aiomatic_task_input, #aiomatic_task_constraints, #aiomatic_task_output')
                .prop('disabled', true);
        } else {
            $('#aiomatic-task-modal h2').text('" . esc_html__('Start Agent Task', 'aiomatic-automatic-ai-content-writer') . "');
            $('#aiomatic_stop_task_btn').hide();
            $('#aiomatic_start_task_btn').show();

            $('#aiomatic_task_goal, #aiomatic_task_input, #aiomatic_task_constraints, #aiomatic_task_output')
                .prop('disabled', false);
        }
    }

    $('#aiomatic_allow_all_tools').on('change', function(){
        if ($(this).is(':checked')) {
            $('#aiomatic_tools_list').hide();
        } else {
            $('#aiomatic_tools_list').show();
        }
    });

    $('#aiomatic_allow_all_tools').trigger('change');

    $(document).on('click', '.aiomatic-tools-toggle', function () {
        const xlist = $(this).next('.aiomatic-tools-list');
        const willOpen = !xlist.is(':visible');
        xlist.slideToggle(150);
        $(this).text((willOpen ? '▼' : '▶') + ' Available Tools (' + xlist.children().length + ')');
    });

    $(document).on('click', '.aiomatic-tool-header', function () {
        $(this).next('.aiomatic-tool-body').slideToggle(120);
    });

    $(document).on('click', '.aiomatic-modal-close', function () {
        $(this).closest('.aiomatic-modal').fadeOut(150);
    });

    window.aiomaticSetTaskModalState = aiomaticSetTaskModalState;
    $(document).on('click', '.aiomatic-open-task-modal', function(e){
        e.preventDefault();
        const agentId = $(this).data('agent-id');
        const status  = $(this).data('agent-status') || 'idle';

        $('#aiomatic_task_agent_id').val(agentId);

        if (typeof window.aiomaticSetTaskModalState === 'function') {
            window.aiomaticSetTaskModalState(status);
        }

        $('#aiomatic-task-modal').fadeIn(150);
    });
});
    ");
});
add_action('add_meta_boxes', function () {
    add_meta_box(
        'aiomatic_agent_settings',
        esc_html__('Agent Settings', 'aiomatic-automatic-ai-content-writer'),
        'aiomatic_agent_settings_metabox',
        'aiomatic_agent',
        'side',
        'high'
    );
});

add_filter('manage_aiomatic_agent_posts_columns', function($cols){
    $new = [];

    foreach ($cols as $k => $v) {
        if ($k === 'title') {
            $new['agent_avatar'] = esc_html__('Avatar', 'aiomatic-automatic-ai-content-writer');
        }
        $new[$k] = $v;

        if ($k === 'title') {
            $new['agent_status'] = esc_html__('Status', 'aiomatic-automatic-ai-content-writer');
            $new['agent_last']   = esc_html__('Last Activity', 'aiomatic-automatic-ai-content-writer');
            $new['agent_actions'] = esc_html__('Actions', 'aiomatic-automatic-ai-content-writer');
        }
    }

    return $new;
});
add_action('manage_aiomatic_agent_posts_custom_column', function($col, $post_id){

    if ($col === 'agent_avatar') {

        if (has_post_thumbnail($post_id)) {
            echo get_the_post_thumbnail($post_id, [36,36], [
                'style' => 'border-radius:50%; width:36px; height:36px; object-fit:cover;'
            ]);
        } else {
            echo '<img src="' . esc_url( plugin_dir_url(__FILE__) . '../images/placeholder.jpg' ) . '" 
            style="border-radius:50%; width:36px; height:36px; object-fit:cover;" 
            alt="" />';
        }
    }
    if ($col === 'agent_status') {
        $status = get_post_meta($post_id, '_agent_status', true) ?: 'idle';

        $colors = [
            'running'     => '#46b450',
            'paused'      => '#ffb900',
            'interrupted' => '#ff7700',
            'failed'      => '#dc3232',
            'completed'   => '#2271b1',
            'cancelled'   => '#777',
            'scheduled'   => '#8e44ad',
            'idle'        => '#999'
        ];

        $color = $colors[$status] ?? '#999';

        echo '<span class="more-xcss aiomatic-agent-status" 
            data-agent-id="' . esc_attr($post_id) . '" 
            style="background:' . esc_attr($color) . ';">' 
            . esc_html($status) . 
        '</span>';
    }

    if ($col === 'agent_task') {
        $task = get_post_meta($post_id, '_current_task', true);
        $status = get_post_meta($post_id, '_agent_status', true);

        if ($status === 'running') {
            echo '<strong class="color-ai">' . esc_html__('Running:', 'aiomatic-automatic-ai-content-writer') . '</strong><br>';
        }
        if(!is_string($task))
        {
            if(is_array($task) && isset($task['goal']))
            {
                $task = $task['goal'];
            }
            else
            {
                $task = 'New Task';
            }
        }
        echo esc_html(wp_trim_words($task ?: '-', 8));
    }

    if ($col === 'agent_last') {
        $last = get_post_meta($post_id, '_last_activity', true);
        if(is_numeric($last))
        {
            $last = intval($last);
        }
        else
        {
            $last = null;
        }
        echo '<span class="aiomatic-agent-last" data-agent-id="' . esc_attr($post_id) . '">'
            . ($last ? esc_html(wp_date('Y-m-d H:i:s', $last)) : '-') .
        '</span>';
    }
    
    if ($col === 'agent_actions') {
    $status = get_post_meta($post_id, '_agent_status', true) ?: 'idle';

    $stop_url = wp_nonce_url(
        admin_url('admin-post.php?action=aiomatic_stop_task&agent_id=' . $post_id),
        'aiomatic_stop_task'
    );

    echo '<a href="#" class="button aiomatic-open-task-modal"
        data-agent-id="' . esc_attr($post_id) . '"
        data-agent-status="' . esc_attr($status) . '"
        data-stop-url="' . esc_url($stop_url) . '">'
        . esc_html__('Task', 'aiomatic-automatic-ai-content-writer') .
    '</a>';
}
}, 10, 2);
add_action('add_meta_boxes', function () {
    add_meta_box(
        'aiomatic_agent_task_runner',
        esc_html__('Run Task', 'aiomatic-automatic-ai-content-writer'),
        function($post){

            $status_post = get_post_status($post->ID);

            if ($status_post !== 'publish') {
                echo '<p>' . esc_html__('This agent must be published before you can run tasks.', 'aiomatic-automatic-ai-content-writer') . '</p>';
                return;
            }

            $status = get_post_meta($post->ID, '_agent_status', true) ?: 'idle';
            $task   = get_post_meta($post->ID, '_current_task', true);
            $last   = get_post_meta($post->ID, '_last_activity', true);

            if (!is_string($task)) {
                $task = is_array($task) && isset($task['goal']) ? $task['goal'] : 'New Task';
            }

            $colors = [
                'running'     => '#46b450',
                'paused'      => '#ffb900',
                'interrupted' => '#ff7700',
                'failed'      => '#dc3232',
                'completed'   => '#2271b1',
                'cancelled'   => '#777',
                'scheduled'   => '#8e44ad',
                'idle'        => '#999'
            ];

            $color = $colors[$status] ?? '#999';

            echo '<div id="aiomatic-agent-monitor" data-agent-id="' . esc_attr($post->ID) . '" class="aiomatic-monitor">';

            echo '<div class="aiomatic-monitor-status">';
            echo '<span class="aiomatic-status-badge" style="background:' . esc_attr($color) . ';">' . esc_html($status) . '</span>';
            echo '</div>';

            echo '<div class="aiomatic-monitor-section">';
            echo '<div class="aiomatic-label">' . esc_html__('Current Task', 'aiomatic-automatic-ai-content-writer') . '</div>';
            echo '<div id="aiomatic-agent-task" class="aiomatic-value">' . esc_html(wp_trim_words($task ?: '-', 12)) . '</div>';
            echo '</div>';

            echo '<div class="aiomatic-monitor-section">';
            echo '<div class="aiomatic-label">' . esc_html__('Last Activity', 'aiomatic-automatic-ai-content-writer') . '</div>';
            echo '<div id="aiomatic-agent-last" class="aiomatic-value">' . ($last ? esc_html(wp_date('Y-m-d H:i:s', intval($last))) : '-') . '</div>';
            echo '</div>';

            echo '<div class="aiomatic-monitor-actions-extended">';
            $id = $post->ID;


            $status = get_post_meta($id, '_agent_status', true) ?: 'idle';

            if ($status === 'running') {
                $stop = wp_nonce_url(
                    admin_url("admin-post.php?action=aiomatic_stop_task&agent_id=$id"),
                    'aiomatic_stop_task'
                );
                echo '<a href="' . esc_url($stop) . '" 
                    class="button button-secondary aiomatic-action-danger"
                    onclick="return confirm(\'' . esc_html__('Stop this agent task?', 'aiomatic-automatic-ai-content-writer') . '\');">
                    <span class="dashicons dashicons-controls-pause"></span> '
                    . esc_html__('Stop', 'aiomatic-automatic-ai-content-writer') . '
                </a>';
            } elseif ($status === 'paused' || $status === 'interrupted') {

                $resume = wp_nonce_url(
                    admin_url("admin-post.php?action=aiomatic_resume_task&agent_id=$id"),
                    'aiomatic_resume_task'
                );

                echo '<a href="' . esc_url($resume) . '" 
                    class="button button-secondary aiomatic-action-success">
                    <span class="dashicons dashicons-controls-play"></span> ' . esc_html__('Resume', 'aiomatic-automatic-ai-content-writer') . '
                </a>';

            } elseif ($status === 'scheduled') {
                $cancel = wp_nonce_url(
                    admin_url("admin-post.php?action=aiomatic_cancel_schedule&agent_id=$id"),
                    'aiomatic_cancel_schedule'
                );
                echo '<a href="' . esc_url($cancel) . '" 
                    class="button button-secondary aiomatic-action-danger"
                    onclick="return confirm(\'' . esc_html__('Cancel the schedule?', 'aiomatic-automatic-ai-content-writer') . '\');">
                    <span class="dashicons dashicons-controls-pause"></span> '
                    . esc_html__('Cancel Schedule', 'aiomatic-automatic-ai-content-writer') . '
                </a>';
            } else {
                echo '<a href="#" 
                    class="button button-secondary aiomatic-action-success start-agent-task"
                    data-id="' . esc_attr($id) . '">
                    <span class="dashicons dashicons-controls-play"></span> '
                    . esc_html__('Start', 'aiomatic-automatic-ai-content-writer') . '
                </a>';
            }

            echo '<a href="#" 
                class="button button-secondary aiomatic-action-logs view-agent-logs"
                data-id="' . esc_attr($id) . '">
                <span class="dashicons dashicons-list-view"></span> '
                . esc_html__('Logs', 'aiomatic-automatic-ai-content-writer') . '
            </a>';

            echo '<a href="#" 
                class="button button-secondary aiomatic-action-warning clear-agent-long-memory"
                data-id="' . esc_attr($id) . '">
                <span class="dashicons dashicons-trash"></span> '
                . esc_html__('Clear', 'aiomatic-automatic-ai-content-writer') . '
            </a>';

            echo '</div>';

            echo '</div>';
        },
        'aiomatic_agent',
        'side',
        'high'
    );
});

add_action('add_meta_boxes', function () {
    add_meta_box(
        'aiomatic_agent_runtime',
        'Agent Runtime',
        function($post){
            $status = get_post_meta($post->ID, '_agent_status', true) ?: 'idle';
            $task   = get_post_meta($post->ID, '_current_task', true);
            $mem    = get_post_meta($post->ID, '_agent_memory', true);

            if (!empty($mem)) {
                $mem = json_decode($mem, true);
            }

            $memory = $mem ? count($mem) : 0;

            echo '<p><strong>' . esc_html__('Status:', 'aiomatic-automatic-ai-content-writer') . '</strong> ' . esc_html($status) . '</p>';
            echo '<p><strong>' . esc_html__('Task:', 'aiomatic-automatic-ai-content-writer') . '</strong><br>' . esc_html(is_string($task) ? $task : '-') . '</p>';
            echo '<p><strong>' . esc_html__('Memory size:', 'aiomatic-automatic-ai-content-writer') . '</strong> ' . esc_html($memory) . ' entries</p>';

            if ($status === 'running') {
                $stop_url = wp_nonce_url(
                    admin_url('admin-post.php?action=aiomatic_stop_task&agent_id=' . $post->ID),
                    'aiomatic_stop_task'
                );

                echo '<p><a class="button button-secondary" href="' . esc_url($stop_url) . '" onclick="return confirm(\'' . esc_html__('Stop this agent task?', 'aiomatic-automatic-ai-content-writer') . '\');">' . esc_html__('Stop Task', 'aiomatic-automatic-ai-content-writer') . '</a></p>';
            }
            elseif ($status === 'scheduled') {
                $cancel = wp_nonce_url(
                    admin_url('admin-post.php?action=aiomatic_cancel_schedule&agent_id=' . $post->ID),
                    'aiomatic_cancel_schedule'
                );

                echo '<p><a class="button button-secondary" href="' . esc_url($cancel) . '" onclick="return confirm(\'' . esc_html__('Cancel this schedule?', 'aiomatic-automatic-ai-content-writer') . '\');">' . esc_html__('Cancel Schedule', 'aiomatic-automatic-ai-content-writer') . '</a></p>';
            }
        },
        'aiomatic_agent',
        'side',
        'high'
    );
});
add_action('add_meta_boxes', function () {
    add_meta_box(
        'aiomatic_agent_logs',
        'Recent Activity',
        function($post){

            global $wpdb;

            $table = $wpdb->prefix . 'aiomatic_agent_runs';

            $logs = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM $table WHERE agent_id = %d ORDER BY id DESC LIMIT 10",
                    $post->ID
                )
            );

            echo '<div class="max-css">';

            if ($logs) {
                foreach ($logs as $log) {
                    echo '<div class="minimal-css">';
                    echo '<strong>' . esc_html($log->type) . '</strong><br>';
                    echo '<small>' . esc_html($log->created_at) . '</small>';
                    echo '</div>';
                }
            } else {
                echo esc_html__('No logs.', 'aiomatic-automatic-ai-content-writer');
            }

            echo '</div>';

        },
        'aiomatic_agent',
        'normal',
        'high'
    );
});
add_action('admin_post_aiomatic_resume_task', function(){

    if (!current_user_can('edit_posts')) {
        wp_die('Permission denied.');
    }

    if (
        !isset($_REQUEST['_wpnonce']) ||
        !wp_verify_nonce($_REQUEST['_wpnonce'], 'aiomatic_resume_task')
    ) {
        wp_die('Invalid nonce');
    }

    $id = intval($_REQUEST['agent_id']);
    if (!$id) {
        wp_die('Invalid agent ID.');
    }

    $agent = new Aiomatic_Agent($id);
    $agent->aiomatic_resume_agent();

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
});
add_action('admin_post_aiomatic_stop_task', function(){

    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Permission denied.', 'aiomatic-automatic-ai-content-writer'));
    }
    if (
        !isset($_REQUEST['_wpnonce']) ||
        !wp_verify_nonce($_REQUEST['_wpnonce'], 'aiomatic_stop_task')
    ) {
        wp_die('Invalid nonce');
    }
    $id = intval($_REQUEST['agent_id']);
    if (!$id) {
        wp_die(esc_html__('Invalid agent ID.', 'aiomatic-automatic-ai-content-writer'));
    }
    $agent = new Aiomatic_Agent($id);
    $agent->stop_task();

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
});
add_action('admin_post_aiomatic_cancel_schedule', function(){

    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Permission denied.', 'aiomatic-automatic-ai-content-writer'));
    }
    if (
        !isset($_REQUEST['_wpnonce']) ||
        !wp_verify_nonce($_REQUEST['_wpnonce'], 'aiomatic_cancel_schedule')
    ) {
        wp_die('Invalid nonce');
    }
    $id = intval($_REQUEST['agent_id']);
    if (!$id) {
        wp_die(esc_html__('Invalid agent ID.', 'aiomatic-automatic-ai-content-writer'));
    }
    $agent = new Aiomatic_Agent($id);
    $agent->cancel_schedule();

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
});
add_action('save_post_aiomatic_agent', function ($post_id) {

    if (!isset($_POST['aiomatic_agent_nonce']) ||
        !wp_verify_nonce($_POST['aiomatic_agent_nonce'], 'aiomatic_agent_save')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    $config = [];

    if (isset($_POST['aiomatic_allow_all_tools'])) {
        $config['allowed_tools'] = null;
    } else {
        $config['allowed_tools'] = isset($_POST['aiomatic_allowed_tools'])
            ? array_map('sanitize_text_field', (array) $_POST['aiomatic_allowed_tools'])
            : [];
    }

    $config['max_steps'] = isset($_POST['aiomatic_max_steps']) ? intval($_POST['aiomatic_max_steps']) : 20;
    $config['max_tool_retries'] = isset($_POST['aiomatic_max_tool_retries']) ? intval($_POST['aiomatic_max_tool_retries']) : 3;

    $config['allow_delegation'] = isset($_POST['aiomatic_allow_delegation']);
    $config['planning_enabled'] = isset($_POST['aiomatic_planning_enabled']);
    $config['planning_required'] = isset($_POST['aiomatic_planning_required']);
    $config['tool_calls_enabled'] = isset($_POST['aiomatic_tool_calls_enabled']);
    $config['short_term_memory_enabled'] = isset($_POST['aiomatic_short_mem']);
    $long_mem_available = aiomatic_long_term_memory_available();
    $config['long_term_memory_enabled'] = $long_mem_available
        ? isset($_POST['aiomatic_long_mem'])
        : false;
    update_post_meta($post_id, '_agent_config', $config);

    if (isset($_POST['aiomatic_agent_model'])) {
        update_post_meta(
            $post_id,
            '_model',
            sanitize_text_field($_POST['aiomatic_agent_model'])
        );
    }

    if (isset($_POST['aiomatic_agent_description'])) {
        update_post_meta(
            $post_id,
            'aiomatic_agent_description',
            sanitize_text_field($_POST['aiomatic_agent_description'])
        );
    }

    if (isset($_POST['aiomatic_agent_expertise'])) {
        update_post_meta(
            $post_id,
            'aiomatic_agent_expertise',
            sanitize_text_field($_POST['aiomatic_agent_expertise'])
        );
    }

});
function aiomatic_tooltip($text) {
    return '<span class="aiomatic-tooltip" title="' . esc_attr($text) . '">?</span>';
}
function aiomatic_agent_settings_metabox($post)
{
    wp_nonce_field('aiomatic_agent_save', 'aiomatic_agent_nonce');

    $config = get_post_meta($post->ID, '_agent_config', true);
    $config = is_array($config) ? $config : [];

    $allowed_tools = $config['allowed_tools'] ?? null;
    $max_steps = $config['max_steps'] ?? 20;
    $max_tool_retries = $config['max_tool_retries'] ?? 3;

    $allow_delegation = $config['allow_delegation'] ?? true;
    $planning_enabled = $config['planning_enabled'] ?? false;
    $planning_required = $config['planning_required'] ?? false;
    $tool_calls_enabled = $config['tool_calls_enabled'] ?? true;
    $short_mem = $config['short_term_memory_enabled'] ?? true;
    $long_mem = $config['long_term_memory_enabled'] ?? true;
    $long_mem_available = aiomatic_long_term_memory_available();

    $default_model = AIMOGEN_DEFAULT_MODEL;
    if (!$long_mem_available) {
        $long_mem = false;
    }
    $model       = get_post_meta($post->ID, '_model', true);
    if(empty($model))
    {
        $model = $default_model;
    }
    $description = get_post_meta($post->ID, 'aiomatic_agent_description', true);
    $expertise   = get_post_meta($post->ID, 'aiomatic_agent_expertise', true);

    $aiomatic_agent_models = aiomatic_get_all_models();

    if (is_array($aiomatic_agent_models)) {
        $aiomatic_agent_models = array_values(array_unique($aiomatic_agent_models));
        if (!in_array($default_model, $aiomatic_agent_models, true)) {
            array_unshift($aiomatic_agent_models, $default_model);
        }
        $aiomatic_agent_models = array_slice($aiomatic_agent_models, 0, 30);
    } else {
        $aiomatic_agent_models = [$default_model];
    }
    ?>

    <p>
        <label><strong><?php esc_html_e( 'Model', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
        <?php echo aiomatic_tooltip(__('Select the AI model used by this agent. More advanced models provide better reasoning but may be slower or more expensive.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
        <select name="aiomatic_agent_model" class="widefat">
            <?php foreach ($aiomatic_agent_models as $m): ?>
                <option value="<?php echo esc_attr($m); ?>" <?php selected($model ?: $default_model, $m); ?>>
                    <?php echo esc_html($m); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </p>

    <p>
        <label><strong><?php esc_html_e( 'Description', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
    <?php echo aiomatic_tooltip(__('Short summary of what this agent does. Used internally for context and delegation decisions.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
        <textarea name="aiomatic_agent_description" class="widefat" placeholder="<?php esc_html_e( 'Enter a brief description of the agent\'s purpose...', 'aiomatic-automatic-ai-content-writer' ); ?>"><?php echo esc_textarea($description); ?></textarea>
    </p>

    <p>
        <label><strong><?php esc_html_e( 'Expertise', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
    <?php echo aiomatic_tooltip(__('Defines the agent\'s knowledge domain. Helps improve reasoning and tool selection.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
        <textarea name="aiomatic_agent_expertise" class="widefat" placeholder="<?php esc_html_e( 'Describe the agent\'s areas of expertise...', 'aiomatic-automatic-ai-content-writer' ); ?>"><?php echo esc_textarea($expertise); ?></textarea>
    </p>
    <p>
        <label><strong><?php esc_html_e( 'Allowed Tools', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
    <?php echo aiomatic_tooltip(__('Restrict which tools the agent can use. Disable unused tools to improve reliability and reduce hallucinations.', 'aiomatic-automatic-ai-content-writer' )); ?></label>

        <label>
            <input type="checkbox" id="aiomatic_allow_all_tools" name="aiomatic_allow_all_tools"
                <?php checked($allowed_tools === null); ?>>
            <?php esc_html_e( 'Allow all tools (default)', 'aiomatic-automatic-ai-content-writer' ); ?>
            <?php echo aiomatic_tooltip(__('When enabled, the agent can access all available tools. Disable to manually control tool access.', 'aiomatic-automatic-ai-content-writer' )); ?>
        </label>

    <div id="aiomatic_tools_list" class="new-ccss" style="margin-top:6px; <?php echo ($allowed_tools === null) ? 'display:none;' : ''; ?>">
<?php
$all_tools = Aiomatic_Agent::get_agent_tools();
$groups    = aiomatic_get_tool_groups();

$rendered = [];

foreach ($groups as $category => $tool_names) {

    $has_tools = false;
    foreach ($tool_names as $tool_name) {
        if (isset($all_tools[$tool_name])) {
            $has_tools = true;
            break;
        }
    }

    if (!$has_tools) {
        continue;
    }

    echo '<div class="aiomatic-tool-group">';
    echo '<strong style="display:block;margin:8px 0 4px;">' . esc_html($category) . '</strong>';

    foreach ($tool_names as $tool_name) {

        if (!isset($all_tools[$tool_name])) {
            continue;
        }

        $rendered[$tool_name] = true;

        $checked = is_array($allowed_tools) && in_array($tool_name, $allowed_tools);
        ?>
        <label>
            <input type="checkbox" name="aiomatic_allowed_tools[]" value="<?php echo esc_attr($tool_name); ?>" <?php checked($checked); ?>>
            <?php echo esc_html($tool_name); ?>
        </label>
        <?php
    }

    echo '</div>';
}

$remaining = array_diff_key($all_tools, $rendered);

if (!empty($remaining)) {

    echo '<div class="aiomatic-tool-group">';
    echo '<strong style="display:block;margin:8px 0 4px;">Other</strong>';

    foreach ($remaining as $tool_name => $tool) {
        $checked = is_array($allowed_tools) && in_array($tool_name, $allowed_tools);
        ?>
        <label>
            <input type="checkbox" name="aiomatic_allowed_tools[]" value="<?php echo esc_attr($tool_name); ?>" <?php checked($checked); ?>>
            <?php echo esc_html($tool_name); ?>
        </label>
        <?php
    }

    echo '</div>';
}
?>
</div>
    </p>
    <p>
        <label><strong><?php esc_html_e( 'Max Steps', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
    <?php echo aiomatic_tooltip(__('Maximum number of reasoning iterations. Higher values allow complex tasks but increase cost and execution time.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br/>
        <input type="number" name="aiomatic_max_steps" value="<?php echo esc_attr($max_steps); ?>" min="1" max="100" class="widefat">
    </p>

    <p>
        <label><strong><?php esc_html_e( 'Max Tool Retries', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
    <?php echo aiomatic_tooltip(__('How many times the agent retries a failed tool call before giving up. Prevents infinite loops on failing tools.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br/>
        <input type="number" name="aiomatic_max_tool_retries" value="<?php echo esc_attr($max_tool_retries); ?>" min="0" max="10" class="widefat">
    </p>
    <p><strong><?php esc_html_e( 'Behavior', 'aiomatic-automatic-ai-content-writer' ); ?></strong></p>

    <label><input type="checkbox" name="aiomatic_allow_delegation" <?php checked($allow_delegation); ?>> <?php esc_html_e( 'Allow delegation', 'aiomatic-automatic-ai-content-writer' ); ?><?php echo aiomatic_tooltip(__('Allows this agent to assign tasks to other agents. Useful for multi-agent workflows.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
    <label><input type="checkbox" name="aiomatic_planning_enabled" <?php checked($planning_enabled); ?>> <?php esc_html_e( 'Enable planning', 'aiomatic-automatic-ai-content-writer' ); ?><?php echo aiomatic_tooltip(__('Agent creates a plan before executing tasks. Improves performance on complex, multi-step goals.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
    <label><input type="checkbox" name="aiomatic_planning_required" <?php checked($planning_required); ?>> <?php esc_html_e( 'Planning required', 'aiomatic-automatic-ai-content-writer' ); ?><?php echo aiomatic_tooltip(__('Forces the agent to always plan before acting. Useful for strict workflows but may slow execution.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
    <label><input type="checkbox" name="aiomatic_tool_calls_enabled" <?php $tool_models = aiomatic_get_all_models_function(); if(!in_array($model, $tool_models)){ disabled(true); $tool_calls_enabled = false; } checked($tool_calls_enabled); ?>> <?php esc_html_e( 'API level tool calls', 'aiomatic-automatic-ai-content-writer' ); ?><?php echo aiomatic_tooltip(__('Uses native model tool-calling instead of text-based parsing. More reliable and structured, recommended for production.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
    <label><input type="checkbox" name="aiomatic_short_mem" <?php checked($short_mem); ?>> <?php esc_html_e( 'Short-term memory', 'aiomatic-automatic-ai-content-writer' ); ?><?php echo aiomatic_tooltip(__('Stores recent steps during execution. Required for multi-step reasoning and context continuity.', 'aiomatic-automatic-ai-content-writer' )); ?></label><br>
    <label>
        <input type="checkbox"
            name="aiomatic_long_mem"
            <?php checked($long_mem); ?>
            <?php disabled(!$long_mem_available); ?>
        >
        <?php esc_html_e('Long-term memory', 'aiomatic-automatic-ai-content-writer'); ?>
        <?php echo aiomatic_tooltip(__('Stores knowledge across runs using embeddings. Enables the agent to remember past data and reuse it later.', 'aiomatic-automatic-ai-content-writer' )); ?>
    </label>
    <?php if (!$long_mem_available): ?>
        <p class="css-opt">
            <?php esc_html_e('Long Term Memory requires embeddings setup (API key, model and vector database).', 'aiomatic-automatic-ai-content-writer'); ?>
        </p>
    <?php endif; ?>
    <?php
}
function aiomatic_agents_panel()
{
    wp_enqueue_script(
        'aiomatic-agent-admin',
        plugin_dir_url(__FILE__) . '../scripts/aiomatic-agent-admin.js',
        ['jquery'],
        '1.0',
        true
    );
    wp_localize_script('aiomatic-agent-admin', 'aiomaticAgent', [
        'backUrl' => admin_url('admin.php?page=aiomatic_agents_panel#tab-6'),
        'nonce' => wp_create_nonce('aiomatic_agents_nonce'),
        'ajaxurl' => admin_url('admin-ajax.php')
    ]);
    wp_enqueue_style(
        'aiomatic-agent-admin',
        plugin_dir_url(__FILE__) . '../styles/aiomatic-agent-admin.css',
        [],
        '1.0'
    );
    $aiomatic_agent_models = aiomatic_get_all_models();
    $aiomatic_agent_default_model = AIMOGEN_DEFAULT_MODEL;
    if (is_array($aiomatic_agent_models)) {
        $aiomatic_agent_models = array_values(array_unique($aiomatic_agent_models));
        if (!in_array($aiomatic_agent_default_model, $aiomatic_agent_models, true)) {
            array_unshift($aiomatic_agent_models, $aiomatic_agent_default_model);
        }
        $aiomatic_agent_models = array_slice($aiomatic_agent_models, 0, 30);
    } else {
        $aiomatic_agent_models = [$aiomatic_agent_default_model];
    }
    ?>
    <div class="aiomatic-admin-shell">
    <div class="aiomatic-admin-hero">
      <div class="aiomatic-admin-identity">
         <div class="aiomatic-admin-logo">
            <img class="client-logo" src="<?php echo esc_url(plugins_url( '/../images/ai.png', __FILE__ )); ?>" alt="Aimogen" />
         </div>
         <div class="aiomatic-admin-title">
            <div class="aiomatic-admin-title-sub">
               <?php esc_html_e( 'AI Momentum Generator', 'aiomatic-automatic-ai-content-writer' ); ?>
            </div>
            <div class="aiomatic-admin-title-main">
               <?php esc_html_e( 'Aimogen - AI Writer, Editor, ChatBot & Toolkit', 'aiomatic-automatic-ai-content-writer' ); ?>
               <span class="aiomatic-version-pill">
                  <span class="aiomatic-version-pill-dot"></span>
                  <?php esc_html_e( 'Version', 'aiomatic-automatic-ai-content-writer' ); ?> <?php echo esc_html(aimogenpro_get_version());?>
               </span>
            </div>
         </div>
      </div>
      <div class="aiomatic-admin-meta">
         <div class="aiomatic-admin-meta-row">
            <span><?php esc_html_e( 'AI Live inside your dashboard', 'aiomatic-automatic-ai-content-writer' ); ?></span>
         </div>
         <a class="aiomatic-white" href="https://wpbay.com/product/aimogen-pro/" target="_blank">
            <div class="aiomatic-admin-badge">
               <span class="aiomatic-admin-badge-dot"></span><?php esc_html_e( 'Ready when your ideas are', 'aiomatic-automatic-ai-content-writer' ); ?>
            </div>
         </a>
      </div>
   </div>
<div class="aiomatic-admin-layout">
    <aside class="aiomatic-admin-sidebar">
         <div class="aiomatic-admin-sidebar-inner">
            <div class="aiomatic-sidebar-heading">
               <?php esc_html_e( 'AI Agents', 'aiomatic-automatic-ai-content-writer' ); ?>
            </div>
            <div class="aiomatic-sidebar-nav">
               <nav class="nav-tab-wrapper">
                  <a href="#tab-1" class="aiomatic-nav-tab">
                     <span class="aiomatic-sidebar-icon">▶︎</span>
                     <span class="aiomatic-sidebar-label"><?php echo esc_html__("Tutorial", 'aiomatic-automatic-ai-content-writer');?></span>
                  </a>
                  <a href="#tab-6" class="aiomatic-nav-tab">
                     <span class="aiomatic-sidebar-icon">⧓</span>
                     <span class="aiomatic-sidebar-label"><?php echo esc_html__("Manage Agents", 'aiomatic-automatic-ai-content-writer');?></span>
                  </a>
               </nav>
            </div>
            <div class="aiomatic-sidebar-footer">
               <strong><?php esc_html_e( 'Need a quick start?', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
               <span><?php esc_html_e( '1. Set up your custom AI Agents.', 'aimogen' ); ?></span>
               <span><?php esc_html_e( '2. Add custom knowledge to them.', 'aimogen' ); ?></span>
               <span><?php esc_html_e( '3. Give tasks to them and let them run on their own.', 'aimogen' ); ?></span>
               <span>
                  <?php esc_html_e( 'Watch tutorials on', 'aiomatic-automatic-ai-content-writer' ); ?>
                  <a href="https://www.youtube.com/channel/UCVLIksvzyk-D_oEdHab2Lgg" target="_blank" rel="noopener noreferrer">CodeRevolutionTV</a>
               </span>
            </div>
         </div>
      </aside>
<section class="aiomatic-admin-main">
<div class="gs_popuptype_holder seo_pops">
    <div class="wrap aiomatic-admin">
        <div id="tab-1" class="tab-content">
        <br/>
<h3><?php echo esc_html__("What are AI Agents?", 'aiomatic-automatic-ai-content-writer');?></h3>

<p>
<?php echo wp_kses_post(__(
'<strong>AI Agents are not just another prompt box.</strong><br><br>

When you use a normal AI prompt, you ask once and get a response. That\'s it. An agent works differently. You give it a <strong>goal</strong>, and it keeps going. It decides what to do next, takes an action, evaluates the result, and continues step by step until it finishes or runs out of limits.<br><br>

That loop is what makes it <strong>powerful</strong>. It is also what makes it <strong>dangerous</strong> if you don\'t control it properly.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Agents are autonomous by design.</strong><br><br>

Once started, they will keep thinking, calling tools, and generating outputs without asking you again. If your setup is loose or your limits are too high, they can <strong>burn through tokens very quickly</strong>. That means <strong>real cost</strong>.<br><br>

Because of this, you should treat agents as something you <strong>supervise</strong>, not something you blindly trust.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>This is still a beta feature inside Aiomogen.</strong><br><br>

It works, but it is not foolproof. You will see <strong>unexpected behavior</strong>, inefficient decisions, or strange loops. That is normal at this stage. The system improves as you learn how to guide it.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Creating an agent is about defining behavior.</strong><br><br>

The system prompt is where you shape the agent. If you are vague, the agent will improvise and drift. If you are clear and specific, it becomes <strong>predictable</strong>.<br><br>

Think of it as setting <strong>boundaries</strong>, not just giving instructions.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Steps control how long the agent runs.</strong><br><br>

Too few steps and it stops early. Too many and it may wander or loop. There is no perfect number - you <strong>tune it per task</strong>.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Tools define what the agent can do.</strong><br><br>

Without tools, the agent only generates text. With tools, it can <strong>take actions</strong>.<br><br>

More tools increase power, but also increase mistakes. In practice, <strong>limiting tools</strong> often gives better results.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Memory affects consistency.</strong><br><br>

<strong>Short-term memory</strong> keeps track of the current run.<br>
<strong>Long-term memory</strong> persists data across runs.<br><br>

Useful when needed, but unnecessary memory adds <strong>overhead and cost</strong>.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Planning changes behavior.</strong><br><br>

Without planning, the agent reacts step by step. With planning, it builds a plan first, then executes it.<br><br>

For complex tasks, planning improves results, but adds <strong>latency and cost</strong>.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Agents can delegate work.</strong><br><br>

This only works if each agent has a <strong>clear role</strong>. Otherwise, delegation becomes random and ineffective.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Model choice matters.</strong><br><br>

Some models handle tools properly, others don\'t. With proper tool support, results are <strong>more reliable</strong>. Without it, the agent is guessing.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>How to use it:</strong><br><br>

Create an agent, define its behavior, give it a goal, and run it.<br><br>

If it fails, don\'t guess - <strong>check the logs</strong>.<br>
You will see exactly what it thought, did, and received. That is how you improve it.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<ul>
    <li><?php echo esc_html__('An SEO agent that audits a page and suggests improvements.', 'aiomatic-automatic-ai-content-writer'); ?></li>
    <li><?php echo esc_html__('A content agent that researches and writes structured articles.', 'aiomatic-automatic-ai-content-writer'); ?></li>
    <li><?php echo esc_html__('A data agent that pulls and summarizes API data.', 'aiomatic-automatic-ai-content-writer'); ?></li>
    <li><?php echo esc_html__('A workflow agent that chains multiple tools into a process.', 'aiomatic-automatic-ai-content-writer'); ?></li>
</ul>

<p>
<?php echo esc_html__('In all cases, results depend on how well you define the agent.', 'aiomatic-automatic-ai-content-writer'); ?>
</p>
<p>
<?php echo wp_kses_post(__(
'<strong>Running agents via WP-CLI (recommended for heavy tasks).</strong><br><br>

By default, agents run inside WordPress using AJAX or wp_cron. This works, but it comes with limitations like <strong>execution timeouts</strong>, <strong>memory limits</strong>, and fragmented runs.<br><br>

WP-CLI removes those limits.<br>
You can run agents directly from the server, without browser or request restrictions. This allows <strong>long-running tasks</strong>, better stability, and more predictable execution.<br><br>

Example:<br>
<code>wp aiomatic-agent 123 --task="Write a full SEO audit"</code><br><br>

This runs the agent continuously until it finishes, instead of stopping and resuming. For complex workflows, this makes a significant difference.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>

<p>
<?php echo wp_kses_post(__(
'<strong>Replacing wp_cron with real server cron.</strong><br><br>

wp_cron depends on site traffic. If your site has low activity, scheduled tasks may run late or not at all. For agents, this can lead to <strong>delays</strong> and <strong>inconsistent behavior</strong>.<br><br>

A better approach is to disable wp_cron and use a real server cron job that triggers WP-CLI.<br><br>

Example cron job:<br>
<code>* * * * * wp aiomatic-agent 123 --quiet</code><br><br>

This ensures agents run on a <strong>fixed schedule</strong>, independent of visitors. It is more reliable, faster, and closer to how production systems operate.<br><br>

For serious use, combining <strong>WP-CLI + real cron</strong> is the recommended setup.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>
<p>
<?php echo wp_kses_post(__(
'<strong>Remember, agents are not a one-click feature.</strong><br><br>

At first, it may feel unpredictable. That is normal. Once you understand how agents behave, they become extremely useful.<br><br>

The difference is not in the tool - it is in how you <strong>configure it</strong>.',
'aiomatic-automatic-ai-content-writer'
)); ?>
</p>
<h3><?php echo esc_html__("AI Agents Tutorial Video", 'aiomatic-automatic-ai-content-writer');?></h3>
<?php $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
if(!isset($aiomatic_Main_Settings['hide_videos']) || trim($aiomatic_Main_Settings['hide_videos']) != 'on'){
?>
<p class="cr_center"><div class="embedtool"><iframe src="https://www.youtube.com/embed/rT1BiSgimbQ" frameborder="0" allowfullscreen></iframe></div></p>   
<?php
}
$add_agent_url     = admin_url('post-new.php?post_type=aiomatic_agent');
?>
</div>
<div id="tab-6" class="tab-content">

    <?php if (!empty($_GET['aiomatic_agent_created'])) : ?>
        <div class="notice notice-success is-dismissible">
            <p><?php echo esc_html__('Agent created successfully.', 'aiomatic-automatic-ai-content-writer'); ?></p>
        </div>
    <?php endif; ?>

    <div class="aiomatic-header aiomatic-header-manage">
        <div class="aiomatic-header-copy">
            <h1><?php echo esc_html__('AI Agents', 'aiomatic-automatic-ai-content-writer'); ?></h1>
            <p><?php echo esc_html__('Manage your AI Agents.', 'aiomatic-automatic-ai-content-writer'); ?></p>
        </div>

        <div class="aiomatic-header-actions">
            <a class="button button-primary" href="<?php echo esc_url($add_agent_url); ?>">
                <?php echo esc_html__('Add New Agent', 'aiomatic-automatic-ai-content-writer'); ?>
            </a>
            <button id="aiomatic_backup_agents" class="button button-primary">
                <?php echo esc_html__("Backup/Restore Agents", 'aiomatic-automatic-ai-content-writer'); ?>
            </button>
        </div>
    </div>

    <div class="aiomatic-native-table">

<?php
if (!class_exists('WP_Posts_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php';
}

$post_type = 'aiomatic_agent';

set_current_screen('edit-' . $post_type);

global $hook_suffix;
$hook_suffix = 'edit.php';

$_REQUEST['post_type'] = $post_type;
$_GET['post_type']     = $post_type;
if (isset($_GET['post_status'])) {
    $_REQUEST['post_status'] = sanitize_text_field($_GET['post_status']);
}
if (isset($_GET['s'])) {
    $_REQUEST['s'] = sanitize_text_field($_GET['s']);
}
$list_table = new WP_Posts_List_Table([
    'screen' => get_current_screen(),
]);
$list_table->prepare_items();
?>
<div class="wrap">
    <?php
    $list_table->views();
    ?>
<form method="get" class="margin-10">
    <input type="hidden" name="page" value="aiomatic_agents_panel">
    <?php if (!empty($_GET['post_status'])): ?>
        <input type="hidden" name="post_status" value="<?php echo esc_attr($_GET['post_status']); ?>">
    <?php endif; ?>

    <p class="search-box">
        <input type="search"
               name="s"
               value="<?php echo isset($_GET['s']) ? esc_attr($_GET['s']) : ''; ?>"
               placeholder="<?php echo esc_html__('Search agents...', 'aiomatic-automatic-ai-content-writer'); ?>">
        <button class="button"><?php echo esc_html__('Search', 'aiomatic-automatic-ai-content-writer'); ?></button>
    </p>
</form>
    <form method="get">
        <input type="hidden" name="page" value="aiomatic_agents_panel">
        <input type="hidden" name="post_type" value="<?php echo esc_attr($post_type); ?>">
        <?php

        $list_table->display();
        ?>
    </form>
</div>
    </div>
</div>
</div>
</div>
<div id="aiomatic-backup-modal" class="codemodalfzr">
    <div class="codemodalfzr-content">
        <div class="codemodalfzr-header">
            <span id="aiomatic_close_backup_agents" class="codeclosefzr">&times;</span>
            <h2><span class="cr_color_white">
                <?php echo esc_html__("Backup/Restore Agents", 'aiomatic-automatic-ai-content-writer');?>
            </span></h2>
        </div>

        <div class="codemodalfzr-body">
        <div class="table-responsive">
        <br/>

<?php $max = wp_max_upload_size(); ?>

<hr/>

<div class="aiomatic-loader-bubble">
<h3 class="margin5"><?php echo esc_html__("Restore Agents From File", 'aiomatic-automatic-ai-content-writer');?>:</h3>

<table class="form-table">
<tbody>

<tr>
    <th><?php echo esc_html__("Backup File (*.json)", 'aiomatic-automatic-ai-content-writer');?></th>
    <td><input type="file" id="aiomatic_agents_upload" accept=".json"></td>
</tr>

<tr>
    <th><?php echo esc_html__("Overwrite Existing", 'aiomatic-automatic-ai-content-writer');?></th>
    <td><input type="checkbox" id="aiomatic_agents_overwrite" value="1"></td>
</tr>

<tr>
    <td colspan="2">
        <div class="aiomatic_upload_success aiomatic_none margin5 colorgr"></div>
        <div class="aiomatic_progress aiomatic_none"><span></span><small>Uploading</small></div>
        <div class="aiomatic-error-msg"></div>
    </td>
</tr>

<tr>
    <td colspan="2">
        <button class="button button-primary widefat" id="aiomatic_agents_import_btn">
            <?php echo esc_html__("Import Agents", 'aiomatic-automatic-ai-content-writer');?>
        </button>
        <p><?php echo esc_html__("Max file size:", 'aiomatic-automatic-ai-content-writer');?> <?php echo esc_html(size_format($max));?></p>
    </td>
</tr>

</tbody>
</table>
</div>

<br/><hr/>

<div class="aiomatic-loader-bubble">
<h3><?php echo esc_html__('Backup Current Agents To File:', 'aiomatic-automatic-ai-content-writer');?></h3>

<form method="post">
    <input type="hidden" name="aiomatic_nonce" value="<?php echo esc_attr(wp_create_nonce('aiomatic_agents'));?>">
    <input type="submit" name="aiomatic_download_agents_to_file"
        class="button button-primary widefat"
        value="<?php echo esc_attr__('Backup Agents To File', 'aiomatic-automatic-ai-content-writer');?>">
</form>
</div>

<br/><hr/>

<div class="aiomatic-loader-bubble">
<h3><?php echo esc_html__("Import Default Agents", 'aiomatic-automatic-ai-content-writer');?></h3>

<button class="button button-primary widefat" id="aiomatic_agents_default_btn">
    <?php echo esc_html__("Import Default Agents", 'aiomatic-automatic-ai-content-writer');?>
</button>
</div>

</div>
</div>
</div>
</div>
<div id="aiomatic-task-modal" class="aiomatic-modal">
    <div class="aiomatic-modal-content aiomatic-task-modal">
        <input type="hidden" id="aiomatic_task_agent_id">
        <input type="hidden" id="aiomatic_task_agent_status" value="idle">
        <input type="hidden" id="aiomatic_task_stop_url" value="">
        <span class="aiomatic-modal-close">&times;</span>

        <h2><?php echo esc_html__('Start Agent Task', 'aiomatic-automatic-ai-content-writer'); ?></h2>
        <div class="aiomatic-field">
            <div class="aiomatic-goal-row">
                <label><?php echo esc_html__('Goal (be as descriptive as possible) *', 'aiomatic-automatic-ai-content-writer'); ?></label>
                <button type="button" id="aiomatic_refine_goal" class="button aiomatic-refine-btn">
                    ✨ <?php echo esc_html__('Refine with AI', 'aiomatic-automatic-ai-content-writer'); ?>
                </button>
            </div>
            <textarea id="aiomatic_task_goal" placeholder="<?php echo esc_html__('What should the agent achieve?', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>
        </div>
        
        <div class="aiomatic-toggle-wrapper">
            <button type="button" id="aiomatic_toggle_advanced" class="aiomatic-toggle-btn">
                <span><?php echo esc_html__('Advanced Options', 'aiomatic-automatic-ai-content-writer'); ?></span>
                <span class="aiomatic-icon">▼</span>
            </button>
        </div>
        <div id="aiomatic_advanced_fields" class="aiomatic-extra-fields" style="display: none;">
            <div class="aiomatic-field">
                <label><?php echo esc_html__('Input / Context', 'aiomatic-automatic-ai-content-writer'); ?></label>
                <textarea id="aiomatic_task_input" placeholder="<?php echo esc_html__('Optional context, keywords, URLs, data...', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>
            </div>

            <div class="aiomatic-field">
                <label><?php echo esc_html__('Constraints', 'aiomatic-automatic-ai-content-writer'); ?></label>
                <textarea id="aiomatic_task_constraints" placeholder="<?php echo esc_html__('One rule per line. Example: Max 1000 words', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>
            </div>

            <div class="aiomatic-field">
                <label><?php echo esc_html__('Output Format', 'aiomatic-automatic-ai-content-writer'); ?></label>
                <input type="text" id="aiomatic_task_output" placeholder="<?php echo esc_html__('e.g. HTML article, JSON, bullet list', 'aiomatic-automatic-ai-content-writer'); ?>">
            </div>
        </div>
        <div class="aiomatic-field">
            <label><?php echo esc_html__('Execution', 'aiomatic-automatic-ai-content-writer'); ?></label>

            <div class="aiomatic-schedule-row">
                <label style="margin-right:15px;">
                    <input type="radio" name="aiomatic_schedule_type" value="now" checked>
                    <?php echo esc_html__('Run now', 'aiomatic-automatic-ai-content-writer'); ?>
                </label>

                <label>
                    <input type="radio" name="aiomatic_schedule_type" value="schedule">
                    <?php echo esc_html__('Schedule', 'aiomatic-automatic-ai-content-writer'); ?>
                </label>
            </div>

            <div id="aiomatic_schedule_picker" style="display:none; margin-top:10px;">
                <small>
                    <?php
                    $tz = wp_timezone_string();
                    echo esc_html__('Server time:', 'aiomatic-automatic-ai-content-writer'); ?>
                    <span id="aiomatic-server-time">
                        <?php echo esc_html( current_time('Y-m-d H:i:s') ); ?>
                    </span>
                    (<?php echo esc_html($tz ?: 'UTC'); ?>)
                </small>
                <input type="datetime-local" id="aiomatic_schedule_datetime">
            </div>
        </div>
        <div class="aiomatic-modal-actions">
            <button type="button" class="button button-primary" id="aiomatic_start_task_btn">
                <?php echo esc_html__('Start Task', 'aiomatic-automatic-ai-content-writer'); ?>
            </button>

            <button type="button" class="button button-primary" id="aiomatic_stop_task_btn" style="display:none;">
                <?php echo esc_html__('Stop Task', 'aiomatic-automatic-ai-content-writer'); ?>
            </button>
        </div>
        <div class="aiomatic-result-wrapper">
            <div class="aiomatic-result-header">
                <span><?php echo esc_html__('Task Output', 'aiomatic-automatic-ai-content-writer'); ?></span>
                <button type="button" id="aiomatic_result_toggle" class="aiomatic-result-btn">
                    ⤢
                </button>
            </div>
            <pre id="aiomatic_task_result"></pre>
        </div>

    </div>
</div>
<div id="aiomatic-logs-modal" class="aiomatic-modal">
    <div class="aiomatic-modal-content aiomatic-logs-modal">

        <span class="aiomatic-modal-close">&times;</span>

        <div class="aiomatic-logs-header">
            <h2><?php echo esc_html__('Agent Logs', 'aiomatic-automatic-ai-content-writer'); ?></h2>

            <div class="aiomatic-logs-actions">
                <select id="aiomatic-log-type-filter">
                    <option value=""><?php echo esc_html__('All Types', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="model_prompt">model_prompt</option>
                    <option value="model_response">model_response</option>
                    <option value="model_error">model_error</option>
                    <option value="tool_call">tool_call</option>
                    <option value="tool_result">tool_result</option>
                    <option value="tool_error">tool_error</option>
                    <option value="final">final</option>
                    <option value="error">error</option>
                </select>

                <button id="aiomatic-delete-logs" class="button button-secondary">
                    <?php echo esc_html__('Delete Logs', 'aiomatic-automatic-ai-content-writer'); ?>
                </button>
            </div>
        </div>

        <input type="hidden" id="aiomatic_logs_agent_id">

        <div id="aiomatic_logs_list" class="the-css-class">
            <div id="aiomatic-load-older-wrapper" style="display:none; text-align:center; margin-bottom:10px;">
                <button id="aiomatic-load-older-logs" class="button">
                    <?php echo esc_html__('Load older logs', 'aiomatic-automatic-ai-content-writer'); ?>
                </button>
            </div>
            <div id="aiomatic_logs_container">
                <div class="aiomatic-logs-loading"><?php echo esc_html__('Loading...', 'aiomatic-automatic-ai-content-writer'); ?></div>
            </div>
        </div>

    </div>
</div>
</section>
    <?php 
    wp_nonce_field('aiomatic_agents_nonce', 'aiomatic_agents_nonce_field'); ?>
    </div>
    </div>
<?php
}
?>