<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Admin Automation Handler
 *
 * Handles automation/workflow-related AJAX requests.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/admin
 */
class Kitsune_AI_Platform_Admin_Automation extends Kitsune_AI_Platform_Admin_Ajax_Base {

    /**
     * Register AJAX hooks.
     */
    public function register_hooks() {
        add_action('wp_ajax_kitsune_ai_platform_get_automation_components', array($this, 'ajax_get_automation_components'));
        add_action('wp_ajax_kitsune_ai_platform_save_workflow', array($this, 'ajax_save_workflow'));
        add_action('wp_ajax_kitsune_ai_platform_get_workflows', array($this, 'ajax_get_workflows'));
        add_action('wp_ajax_kitsune_ai_platform_get_workflow', array($this, 'ajax_get_workflow'));
        add_action('wp_ajax_kitsune_ai_platform_delete_workflow', array($this, 'ajax_delete_workflow'));
        add_action('wp_ajax_kitsune_ai_platform_execute_workflow', array($this, 'ajax_execute_workflow'));
        add_action('wp_ajax_kitsune_ai_platform_toggle_workflow_status', array($this, 'ajax_toggle_workflow_status'));
        add_action('wp_ajax_kitsune_ai_platform_get_logs', array($this, 'ajax_get_logs'));
        add_action('wp_ajax_kitsune_ai_platform_get_log_trace', array($this, 'ajax_get_log_trace'));
        add_action('wp_ajax_kitsune_ai_platform_get_scheduled_tasks', array($this, 'ajax_get_scheduled_tasks'));
        add_action('wp_ajax_kitsune_ai_platform_save_scheduled_task', array($this, 'ajax_save_scheduled_task'));
        add_action('wp_ajax_kitsune_ai_platform_delete_scheduled_task', array($this, 'ajax_delete_scheduled_task'));
        add_action('wp_ajax_kitsune_ai_platform_get_workflow_templates', array($this, 'ajax_get_workflow_templates'));
        add_action('wp_ajax_kitsune_ai_platform_clear_logs',              array($this, 'ajax_clear_logs'));
        add_action('wp_ajax_kitsune_ai_platform_run_scheduled_task_now',   array($this, 'ajax_run_scheduled_task_now'));
        add_action('wp_ajax_kitsune_ai_platform_toggle_scheduled_task',    array($this, 'ajax_toggle_scheduled_task'));
    }

    /**
     * AJAX: Get Automation Components
     */
    public function ajax_get_automation_components() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/automation/class-kitsune-ai-platform-automation-manager.php';
        $manager = Kitsune_AI_Platform_Automation_Manager::get_instance();
        
        if ($manager) {
            wp_send_json(array(
                'triggers' => $manager->get_components()['triggers'],
                'actions'  => $manager->get_components()['actions']
            ));
        } else {
            wp_send_json_error(array('message' => __('Automation Manager not loaded', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Save Workflow
     */
    public function ajax_save_workflow() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $workflow_data = $this->get_post_payload('workflow_data', null);

        if (!is_array($workflow_data)) {
            wp_send_json_error(array('message' => __('Invalid JSON data', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        $model = new Kitsune_AI_Platform_Workflow_Model();

        // Check if updating existing workflow
        $workflow_id = isset($workflow_data['id']) ? intval($workflow_data['id']) : 0;

        // Prepare data for model
        $data = array(
            'name'            => sanitize_text_field($workflow_data['name']),
            'trigger_type'    => sanitize_text_field($workflow_data['trigger_type']),
            'workflow_config' => json_encode($workflow_data['config']),
            'description'     => isset($workflow_data['description']) ? sanitize_text_field($workflow_data['description']) : ''
        );
        $data = apply_filters('kitsune_ai_platform_before_save_workflow_data', $data, $workflow_data, $workflow_id);
        $data = apply_filters(
            $workflow_id > 0 ? 'kitsune_ai_platform_before_update_workflow_data' : 'kitsune_ai_platform_before_create_workflow_data',
            $data,
            $workflow_data,
            $workflow_id
        );

        if (!is_array($data)) {
            wp_send_json_error(array('message' => __('Invalid workflow data', 'kitsune-ai-platform')));
            return;
        }

        if ($workflow_id > 0) {
            // Update existing workflow
            $id = $model->update($workflow_id, $data);
            $message = __('Workflow updated successfully', 'kitsune-ai-platform');
        } else {
            // Create new workflow
            $id = $model->create($data);
            $message = __('Workflow saved successfully', 'kitsune-ai-platform');
        }

        if ($id && !is_wp_error($id)) {
            $saved_workflow_id = $workflow_id > 0 ? $workflow_id : $id;
            $workflow = $model->get_by_id($saved_workflow_id);

            if ($workflow_id > 0) {
                do_action('kitsune_ai_platform_workflow_updated', $saved_workflow_id, $data, $workflow);
                Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                    Kitsune_AI_Platform_Webhook_Events::WORKFLOW_UPDATED,
                    array(
                        'workflow_id' => (int) $saved_workflow_id,
                        'workflow' => $workflow,
                        'data' => $data,
                        'actor_id' => get_current_user_id(),
                    )
                );
            } else {
                do_action('kitsune_ai_platform_workflow_created', $saved_workflow_id, $data, $workflow);
                Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                    Kitsune_AI_Platform_Webhook_Events::WORKFLOW_CREATED,
                    array(
                        'workflow_id' => (int) $saved_workflow_id,
                        'workflow' => $workflow,
                        'data' => $data,
                        'actor_id' => get_current_user_id(),
                    )
                );
            }

            $response_data = array(
                'message'     => $message,
                'workflow_id' => $saved_workflow_id,
            );

            $response_data = apply_filters('kitsune_ai_platform_save_workflow_response', $response_data, $saved_workflow_id, $data, $workflow);
            wp_send_json_success($response_data);
        } else {
            wp_send_json_error(array('message' => __('Failed to save workflow', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Get All Workflows
     */
    public function ajax_get_workflows() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        $model = new Kitsune_AI_Platform_Workflow_Model();

        $workflows = $model->get_all();

        // Enrich with run count from logs
        global $wpdb;
        $logs_table = $wpdb->prefix . 'kitsune_ai_platform_workflow_logs';

        foreach ($workflows as &$workflow) {
            // Get run count
            $run_count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(DISTINCT trace_id) FROM {$logs_table} WHERE workflow_id = %d AND trace_id IS NOT NULL AND trace_id != ''",
                $workflow->id
            ));
            $workflow->run_count = (int)$run_count;

            // Get last run
            $last_run = $wpdb->get_var($wpdb->prepare(
                "SELECT created_at FROM {$logs_table} WHERE workflow_id = %d ORDER BY created_at DESC LIMIT 1",
                $workflow->id
            ));
            $workflow->last_run = $last_run
                ? sprintf(
                    /* translators: %s: Human-readable time difference. */
                    __('%s ago', 'kitsune-ai-platform'),
                    human_time_diff(strtotime($last_run))
                )
                : __('Never', 'kitsune-ai-platform');
        }

        wp_send_json_success(array('workflows' => $workflows));
    }

    /**
     * AJAX: Get Single Workflow
     */
    public function ajax_get_workflow() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $workflow_id = isset($_GET['workflow_id']) ? intval($_GET['workflow_id']) : 0;
        if (!$workflow_id) {
            wp_send_json_error(array('message' => __('Workflow ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        $model = new Kitsune_AI_Platform_Workflow_Model();

        $workflow = $model->get_by_id($workflow_id);

        if (!$workflow) {
            wp_send_json_error(array('message' => __('Workflow not found', 'kitsune-ai-platform')));
            return;
        }

        wp_send_json_success(array('workflow' => $workflow));
    }

    /**
     * AJAX: Delete Workflow
     */
    public function ajax_delete_workflow() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $workflow_id = isset($_POST['workflow_id']) ? intval($_POST['workflow_id']) : 0;
        if (!$workflow_id) {
            wp_send_json_error(array('message' => __('Workflow ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        $model = new Kitsune_AI_Platform_Workflow_Model();
        $workflow = $model->get_by_id($workflow_id);

        $result = $model->delete($workflow_id);

        if ($result) {
            do_action('kitsune_ai_platform_workflow_deleted', $workflow_id, $workflow);
            Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                Kitsune_AI_Platform_Webhook_Events::WORKFLOW_DELETED,
                array(
                    'workflow_id' => (int) $workflow_id,
                    'workflow' => $workflow,
                    'actor_id' => get_current_user_id(),
                )
            );

            $response_data = array('message' => __('Workflow deleted successfully', 'kitsune-ai-platform'));
            $response_data = apply_filters('kitsune_ai_platform_delete_workflow_response', $response_data, $workflow_id, $workflow);
            wp_send_json_success($response_data);
        } else {
            wp_send_json_error(array('message' => __('Failed to delete workflow', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Execute workflow manually.
     */
    public function ajax_execute_workflow() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $workflow_id = 0;
        if (isset($_POST['workflow_id'])) {
            $workflow_id = intval($_POST['workflow_id']);
        } elseif (isset($_POST['id'])) {
            $workflow_id = intval($_POST['id']);
        } elseif (isset($_GET['workflow_id'])) {
            $workflow_id = intval($_GET['workflow_id']);
        } elseif (isset($_GET['id'])) {
            $workflow_id = intval($_GET['id']);
        }

        if (!$workflow_id) {
            wp_send_json_error(array('message' => __('Workflow ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        $model = new Kitsune_AI_Platform_Workflow_Model();
        $workflow = $model->get_by_id($workflow_id);

        if (!$workflow) {
            wp_send_json_error(array('message' => __('Workflow not found', 'kitsune-ai-platform')));
            return;
        }

        $config_json = $workflow->workflow_config ?? $workflow->config ?? '';
        $config = json_decode($config_json, true);
        if (!is_array($config) || !isset($config['trigger'])) {
            wp_send_json_error(array('message' => __('Invalid workflow configuration', 'kitsune-ai-platform')));
            return;
        }

        // Accept optional test context values supplied from the "Run Now" dialog
        $manual_context = array();
        if ( ! empty( $_POST['run_context'] ) ) {
            $run_context_raw = wp_unslash($_POST['run_context']);
            $decoded = json_decode($run_context_raw, true);
            if ( is_array( $decoded ) ) {
                $manual_context = map_deep($decoded, 'sanitize_text_field');
            }
        }

        $context = array_merge(
            $manual_context,
            array(
                'manual'      => true,
                'source'      => 'admin',
                'workflow_id' => $workflow_id,
                'user_id'     => get_current_user_id(),
                'timestamp'   => current_time( 'mysql' ),
            )
        );

        do_action('kitsune_ai_platform_execute_workflow', $workflow_id, $config, $context);

        wp_send_json_success(array(
            'message' => __('Workflow executed successfully', 'kitsune-ai-platform'),
        ));
    }

    /**
     * AJAX: Toggle Workflow Status
     */
    public function ajax_toggle_workflow_status() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $workflow_id = isset($_POST['workflow_id']) ? intval($_POST['workflow_id']) : 0;
        $active = isset($_POST['active']) ? (bool)$_POST['active'] : false;

        if (!$workflow_id) {
            wp_send_json_error(array('message' => __('Workflow ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        $model = new Kitsune_AI_Platform_Workflow_Model();

        $result = $model->update($workflow_id, array('status' => $active ? 'active' : 'inactive'));

        if ($result && !is_wp_error($result)) {
            wp_send_json_success(array(
                'message' => $active ? __('Workflow activated', 'kitsune-ai-platform') : __('Workflow deactivated', 'kitsune-ai-platform')
            ));
        } else {
            wp_send_json_error(array('message' => __('Failed to update workflow status', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Get Logs
     */
    public function ajax_get_logs() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/automation/class-kitsune-ai-platform-automation-logger.php';
        $logger = Kitsune_AI_Platform_Automation_Logger::get_instance();

        // Build filters from request
        $filters = array();
        if (!empty($_GET['workflow_id'])) {
            $filters['workflow_id'] = intval($_GET['workflow_id']);
        }
        if (!empty($_GET['level'])) {
            $filters['level'] = sanitize_text_field($_GET['level']);
        }
        if (!empty($_GET['date_from'])) {
            $filters['date_from'] = sanitize_text_field($_GET['date_from']);
        }
        if (!empty($_GET['date_to'])) {
            $filters['date_to'] = sanitize_text_field($_GET['date_to']);
        }
        if (!empty($_GET['search'])) {
            $filters['search'] = sanitize_text_field($_GET['search']);
        }

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $per_page = isset($_GET['per_page']) ? min(100, max(10, intval($_GET['per_page']))) : 20;

        $result = $logger->get_logs($filters, $page, $per_page);

        // Enrich logs with workflow names
        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';
        foreach ($result['logs'] as &$log) {
            if ($log->workflow_id) {
                $workflow = get_post($log->workflow_id);
                $log->workflow_name = $workflow ? $workflow->post_title : __('Deleted Workflow', 'kitsune-ai-platform');
            } else {
                $log->workflow_name = __('N/A', 'kitsune-ai-platform');
            }
        }

        wp_send_json_success($result);
    }

    /**
     * AJAX: Get Log Details (by trace ID)
     */
    public function ajax_get_log_trace() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $trace_id = isset($_GET['trace_id']) ? sanitize_text_field($_GET['trace_id']) : '';
        if (empty($trace_id)) {
            wp_send_json_error(array('message' => __('Trace ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/automation/class-kitsune-ai-platform-automation-logger.php';
        $logger = Kitsune_AI_Platform_Automation_Logger::get_instance();

        $logs = $logger->get_logs_by_trace($trace_id);

        wp_send_json_success(array('logs' => $logs));
    }

    /**
     * AJAX: Get Scheduled Tasks
     */
    public function ajax_get_scheduled_tasks() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-scheduled-task-model.php';
        $model = new Kitsune_AI_Platform_Scheduled_Task_Model();

        $tasks = $model->get_all();

        wp_send_json_success(array(
            'tasks' => $tasks,
            'frequency_options' => Kitsune_AI_Platform_Scheduled_Task_Model::get_frequency_options()
        ));
    }

    /**
     * AJAX: Save Scheduled Task
     */
    public function ajax_save_scheduled_task() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $task_data = $this->get_post_payload('task_data', null);

        if (!is_array($task_data)) {
            wp_send_json_error(array('message' => __('Invalid JSON data', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-scheduled-task-model.php';
        $model = new Kitsune_AI_Platform_Scheduled_Task_Model();

        $task_id = isset($task_data['id']) ? intval($task_data['id']) : 0;

        $data = array(
            'name'        => sanitize_text_field($task_data['name']),
            'workflow_id' => intval($task_data['workflow_id']),
            'frequency'   => sanitize_text_field($task_data['frequency']),
            'start_date'  => sanitize_text_field($task_data['start_date']),
            'end_date'    => isset($task_data['end_date']) ? sanitize_text_field($task_data['end_date']) : '',
            'time_of_day' => sanitize_text_field($task_data['time_of_day']),
            'active'      => isset($task_data['active']) ? (bool)$task_data['active'] : true
        );

        if ($task_id > 0) {
            $id = $model->update($task_id, $data);
            $message = __('Scheduled task updated successfully', 'kitsune-ai-platform');
        } else {
            $id = $model->create($data);
            $message = __('Scheduled task created successfully', 'kitsune-ai-platform');
        }

        if ($id && !is_wp_error($id)) {
            wp_send_json_success(array(
                'message' => $message,
                'task_id' => $task_id > 0 ? $task_id : $id
            ));
        } else {
            wp_send_json_error(array('message' => __('Failed to save scheduled task', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Delete Scheduled Task
     */
    public function ajax_delete_scheduled_task() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $task_id = isset($_POST['task_id']) ? intval($_POST['task_id']) : 0;
        if (!$task_id) {
            wp_send_json_error(array('message' => __('Task ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-scheduled-task-model.php';
        $model = new Kitsune_AI_Platform_Scheduled_Task_Model();

        $result = $model->delete($task_id);

        if ($result) {
            wp_send_json_success(array('message' => __('Scheduled task deleted successfully', 'kitsune-ai-platform')));
        } else {
            wp_send_json_error(array('message' => __('Failed to delete scheduled task', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Run a scheduled task immediately (manual trigger)
     */
    public function ajax_run_scheduled_task_now() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $task_id = isset($_POST['task_id']) ? intval($_POST['task_id']) : 0;
        if (!$task_id) {
            wp_send_json_error(array('message' => __('Task ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-scheduled-task-model.php';
        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-workflow-model.php';

        $task_model = new Kitsune_AI_Platform_Scheduled_Task_Model();
        $task       = $task_model->get_by_id($task_id);

        if (!$task) {
            wp_send_json_error(array('message' => __('Scheduled task not found', 'kitsune-ai-platform')));
            return;
        }

        $workflow_model = new Kitsune_AI_Platform_Workflow_Model();
        $workflow       = $workflow_model->get_by_id($task->workflow_id);

        if (!$workflow) {
            wp_send_json_error(array('message' => __('Associated workflow not found', 'kitsune-ai-platform')));
            return;
        }

        $config = json_decode($workflow->config, true);
        if (!$config || !isset($config['trigger'])) {
            wp_send_json_error(array('message' => __('Invalid workflow configuration', 'kitsune-ai-platform')));
            return;
        }

        // Record last run and fire the workflow
        $task_model->update_last_run($task_id);

        $context = array(
            'scheduled_task_id'   => $task_id,
            'scheduled_task_name' => $task->name,
            'trigger_type'        => 'scheduled_manual',
            'manual'              => true,
            'user_id'             => get_current_user_id(),
            'execution_time'      => current_time('mysql'),
        );

        do_action('kitsune_ai_platform_execute_workflow', $workflow->id, $config, $context);

        wp_send_json_success(array(
            'message'  => __('Task executed successfully', 'kitsune-ai-platform'),
            'last_run' => sprintf(
                /* translators: %s: Human-readable time difference. */
                __('%s ago', 'kitsune-ai-platform'),
                human_time_diff(time())
            ),
        ));
    }

    /**
     * AJAX: Toggle a scheduled task active / inactive
     */
    public function ajax_toggle_scheduled_task() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $task_id = isset($_POST['task_id']) ? intval($_POST['task_id']) : 0;
        $active  = isset($_POST['active'])  ? (bool) $_POST['active']  : false;

        if (!$task_id) {
            wp_send_json_error(array('message' => __('Task ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-scheduled-task-model.php';
        $model  = new Kitsune_AI_Platform_Scheduled_Task_Model();
        $result = $model->update($task_id, array('active' => $active));

        if ($result && !is_wp_error($result)) {
            wp_send_json_success(array(
                'message' => $active
                    ? __('Scheduled task activated', 'kitsune-ai-platform')
                    : __('Scheduled task deactivated', 'kitsune-ai-platform'),
                'status'  => $active ? 'active' : 'inactive',
                'next_run' => $active
                    ? $this->get_next_run_label($task_id)
                    : null,
            ));
        } else {
            wp_send_json_error(array('message' => __('Failed to update scheduled task status', 'kitsune-ai-platform')));
        }
    }

    /**
     * Helper: get human-readable next-run label for a task
     *
     * @param int $task_id
     * @return string|null
     */
    private function get_next_run_label($task_id) {
        $timestamp = wp_next_scheduled('kitsune_ai_platform_run_scheduled_task', array($task_id));
        if (!$timestamp) {
            return null;
        }
        return human_time_diff(time(), $timestamp) . ' ' . ($timestamp > time() ? __('from now', 'kitsune-ai-platform') : __('ago', 'kitsune-ai-platform'));
    }

    /**
     * AJAX: Clear Workflow Logs
     */
    public function ajax_clear_logs() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        global $wpdb;
        $table = $wpdb->prefix . 'kitsune_ai_platform_workflow_logs';

        $workflow_id = isset($_POST['workflow_id']) ? intval($_POST['workflow_id']) : 0;

        if ($workflow_id > 0) {
            $result = $wpdb->delete($table, array('workflow_id' => $workflow_id), array('%d'));
            $message = __('Logs for workflow cleared successfully', 'kitsune-ai-platform');
        } else {
            $result = $wpdb->query($wpdb->prepare("TRUNCATE TABLE %i", $table));
            $message = __('All logs cleared successfully', 'kitsune-ai-platform');
        }

        if ($result !== false) {
            wp_send_json_success(array('message' => $message));
        } else {
            wp_send_json_error(array('message' => __('Failed to clear logs', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Get Workflow Templates (from JSON files)
     */
    public function ajax_get_workflow_templates() {
        if (!$this->verify_admin_request('automation')) {
            return;
        }

        $templates_dir = KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/templates/';
        $templates = array();

        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }

        if ($wp_filesystem && $wp_filesystem->is_dir($templates_dir)) {
            $files = $wp_filesystem->dirlist($templates_dir);
            if ($files) {
                foreach ($files as $file) {
                    if ($file['type'] !== 'f' || strpos($file['name'], '.json') === false) {
                        continue;
                    }

                    $path = trailingslashit($templates_dir) . $file['name'];
                    $content = $wp_filesystem->get_contents($path);

                    if ($content === false) {
                        error_log('AI Platform: Failed to read workflow template file: ' . $path);
                        continue;
                    }

                    $template = json_decode($content, true);
                    if (!is_array($template) || !isset($template['name'])) {
                        continue;
                    }

                    $template['id'] = basename($file['name'], '.json');
                    $templates[] = $template;
                }
            }
        }

        wp_send_json_success(array('templates' => $templates));
    }

}
