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


/**
 * Aysa Automation Reporter
 * 
 * Handles sending automation reports to external .NET Core API
 * Reports are sent after automated actions complete or on scheduled intervals
 */
class Aysa_Automation_Reporter {
    
    private $api_base_url;
    private $report_endpoint;
    private $api_timeout;
    private $batch_size;
    private $report_frequency;

    private function resolve_api_base_url() {
        if (class_exists('Aysa_API_Config') && method_exists('Aysa_API_Config', 'get_api_base_url')) {
            return rtrim((string) Aysa_API_Config::get_api_base_url(), '/') . '/api/';
        }

        return 'https://api.aysa.ai/api/';
    }
    
    public function __construct() {
        $this->api_base_url = $this->resolve_api_base_url();
        $this->report_endpoint = 'AutomationReport/submit';
        $this->api_timeout = 15;
        $this->batch_size = 50;
        $this->report_frequency = get_option('aysa_automation_report_frequency', 'immediate');
        
        $this->init_hooks();
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        add_action('aysa_automation_action_completed', array($this, 'handle_automation_completion'), 10, 2);
        add_action('aysa_send_automation_report', array($this, 'send_scheduled_report'));
        add_action('wp_ajax_aysa_send_manual_report', array($this, 'handle_manual_report_request'));
        add_action('wp_ajax_aysa_get_task_details', array($this, 'handle_get_task_details'));
        
        if (!wp_next_scheduled('aysa_send_automation_report')) {
            $this->schedule_reports();
        }
    }
    
    /**
     * Handle completion of automated action
     */
    public function handle_automation_completion($action_data, $result) {
        if ($this->report_frequency === 'immediate') {
            $this->send_immediate_report($action_data, $result);
        } else {
            $this->queue_for_batch_report($action_data, $result);
        }
    }
    
    /**
     * Send immediate report for single automation action
     */
    private function send_immediate_report($action_data, $result) {
        $report_data = $this->prepare_automation_report(array($action_data), $result);
        $this->send_report_to_api($report_data);
    }
    
    /**
     * Queue action for batch reporting
     */
    private function queue_for_batch_report($action_data, $result) {
        $queued_reports = get_option('aysa_queued_automation_reports', array());
        
        $queued_reports[] = array(
            'action_data' => $action_data,
            'result' => $result,
            'timestamp' => current_time('mysql'),
            'user_id' => get_current_user_id()
        );
        
        if (count($queued_reports) >= $this->batch_size) {
            $this->send_batch_report($queued_reports);
            delete_option('aysa_queued_automation_reports');
        } else {
            update_option('aysa_queued_automation_reports', $queued_reports);
        }
    }
    
    /**
     * Send batch report for multiple actions
     */
    private function send_batch_report($queued_reports) {
        $report_data = $this->prepare_batch_report($queued_reports);
        $this->send_report_to_api($report_data);
    }
    
    /**
     * Send scheduled report (daily/weekly/monthly)
     */
    public function send_scheduled_report() {
        global $wpdb;
        
        $audit_table = $wpdb->prefix . 'aysa_audit_log';
        $last_report = get_option('aysa_last_automation_report', '1970-01-01 00:00:00');
        
        $automated_actions = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$audit_table} 
             WHERE is_automated = 1 
             AND created_at > %s 
             ORDER BY created_at DESC 
             LIMIT %d",
            $last_report,
            $this->batch_size
        ));
        
        if (!empty($automated_actions)) {
            $report_data = $this->prepare_scheduled_report($automated_actions);
            $success = $this->send_report_to_api($report_data);
            
            if ($success) {
                update_option('aysa_last_automation_report', current_time('mysql'));
            }
        }
        
        $queued_reports = get_option('aysa_queued_automation_reports', array());
        if (!empty($queued_reports)) {
            $this->send_batch_report($queued_reports);
            delete_option('aysa_queued_automation_reports');
        }
    }
    
    /**
     * Prepare automation report data structure
     */
    private function prepare_automation_report($actions, $result = null) {
        $site_info = $this->get_site_info();
        
        return array(
            'reportId' => wp_generate_uuid4(),
            'siteInfo' => $site_info,
            'reportType' => 'immediate',
            'timestamp' => current_time('c'),
            'automationSummary' => $this->generate_automation_summary($actions),
            'actions' => array_map(array($this, 'format_action_data'), $actions),
            'performance' => $this->calculate_performance_metrics($actions),
            'qualityMetrics' => $this->calculate_quality_metrics($actions)
        );
    }
    
    /**
     * Prepare batch report data structure
     */
    private function prepare_batch_report($queued_reports) {
        $site_info = $this->get_site_info();
        $actions = array_column($queued_reports, 'action_data');
        
        return array(
            'reportId' => wp_generate_uuid4(),
            'siteInfo' => $site_info,
            'reportType' => 'batch',
            'timestamp' => current_time('c'),
            'batchSize' => count($queued_reports),
            'timeRange' => array(
                'start' => min(array_column($queued_reports, 'timestamp')),
                'end' => max(array_column($queued_reports, 'timestamp'))
            ),
            'automationSummary' => $this->generate_automation_summary($actions),
            'actions' => array_map(array($this, 'format_queued_action'), $queued_reports),
            'performance' => $this->calculate_performance_metrics($actions),
            'qualityMetrics' => $this->calculate_quality_metrics($actions)
        );
    }
    
    /**
     * Prepare scheduled report data structure
     */
    private function prepare_scheduled_report($audit_entries) {
        $site_info = $this->get_site_info();
        
        return array(
            'reportId' => wp_generate_uuid4(),
            'siteInfo' => $site_info,
            'reportType' => 'scheduled',
            'frequency' => $this->report_frequency,
            'timestamp' => current_time('c'),
            'period' => array(
                'start' => get_option('aysa_last_automation_report', '1970-01-01 00:00:00'),
                'end' => current_time('mysql')
            ),
            'automationSummary' => $this->generate_audit_summary($audit_entries),
            'actions' => array_map(array($this, 'format_audit_entry'), $audit_entries),
            'performance' => $this->calculate_audit_performance($audit_entries),
            'qualityMetrics' => $this->calculate_audit_quality($audit_entries)
        );
    }
    
    /**
     * Get site information for reporting
     */
    private function get_site_info() {
        return array(
            'siteUrl' => get_site_url(),
            'siteName' => get_bloginfo('name'),
            'pluginVersion' => AYSA_VERSION,
            'wordpressVersion' => get_bloginfo('version'),
            'projectId' => $this->get_project_id(),
            'timezone' => wp_timezone_string(),
            'locale' => get_locale()
        );
    }
    
    /**
     * Get project ID from existing domain resolution
     */
    private function get_project_id() {
        $cached_project_id = get_transient('aysa_project_id');
        if ($cached_project_id !== false) {
            return $cached_project_id;
        }
        
        $domain = parse_url(get_site_url(), PHP_URL_HOST);
        $api_url = $this->api_base_url . 'Project/getByDomain/' . urlencode($domain);
        
        $response = wp_remote_get($api_url, array(
            'timeout' => $this->api_timeout,
            'headers' => array(
                'Accept' => 'application/json'
            )
        ));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (isset($data['id'])) {
                set_transient('aysa_project_id', $data['id'], HOUR_IN_SECONDS);
                return $data['id'];
            }
        }
        
        return 0;
    }
    
    /**
     * Generate automation summary
     */
    private function generate_automation_summary($actions) {
        $summary = array(
            'totalActions' => count($actions),
            'actionTypes' => array(),
            'successRate' => 0,
            'averageConfidence' => 0,
            'timeSpent' => 0
        );
        
        $confidence_scores = array();
        $successful_actions = 0;
        
        foreach ($actions as $action) {
            $action_type = $action['action_type'] ?? 'unknown';
            $summary['actionTypes'][$action_type] = ($summary['actionTypes'][$action_type] ?? 0) + 1;
            
            if (isset($action['confidence_score']) && $action['confidence_score'] > 0) {
                $confidence_scores[] = $action['confidence_score'];
            }
            
            if (isset($action['success']) && $action['success']) {
                $successful_actions++;
            }
        }
        
        if (count($actions) > 0) {
            $summary['successRate'] = round(($successful_actions / count($actions)) * 100, 2);
        }
        
        if (count($confidence_scores) > 0) {
            $summary['averageConfidence'] = round(array_sum($confidence_scores) / count($confidence_scores), 2);
        }
        
        return $summary;
    }
    
    /**
     * Generate audit summary from database entries
     */
    private function generate_audit_summary($audit_entries) {
        $summary = array(
            'totalActions' => count($audit_entries),
            'actionTypes' => array(),
            'averageConfidence' => 0,
            'rollbackRate' => 0
        );
        
        $confidence_scores = array();
        $rolled_back = 0;
        
        foreach ($audit_entries as $entry) {
            $action_type = $entry->action_type;
            $summary['actionTypes'][$action_type] = ($summary['actionTypes'][$action_type] ?? 0) + 1;
            
            if ($entry->confidence_score > 0) {
                $confidence_scores[] = $entry->confidence_score;
            }
            
            if ($entry->is_rolled_back) {
                $rolled_back++;
            }
        }
        
        if (count($audit_entries) > 0) {
            $summary['rollbackRate'] = round(($rolled_back / count($audit_entries)) * 100, 2);
        }
        
        if (count($confidence_scores) > 0) {
            $summary['averageConfidence'] = round(array_sum($confidence_scores) / count($confidence_scores), 2);
        }
        
        return $summary;
    }
    
    /**
     * Format action data for API
     */
    private function format_action_data($action) {
        return array(
            'actionId' => wp_generate_uuid4(),
            'actionType' => $action['action_type'] ?? 'unknown',
            'objectId' => $action['object_id'] ?? 0,
            'objectType' => $action['object_type'] ?? 'unknown',
            'confidenceScore' => $action['confidence_score'] ?? null,
            'isAutomated' => $action['is_automated'] ?? false,
            'timestamp' => $action['timestamp'] ?? current_time('c'),
            'userId' => $action['user_id'] ?? get_current_user_id(),
            'oldData' => $action['old_data'] ?? null,
            'newData' => $action['new_data'] ?? null,
            'success' => $action['success'] ?? true
        );
    }
    
    /**
     * Format queued action for API
     */
    private function format_queued_action($queued_item) {
        $action = $this->format_action_data($queued_item['action_data']);
        $action['queuedAt'] = $queued_item['timestamp'];
        $action['result'] = $queued_item['result'];
        return $action;
    }
    
    /**
     * Format audit entry for API
     */
    private function format_audit_entry($entry) {
        return array(
            'actionId' => 'audit_' . $entry->id,
            'actionType' => $entry->action_type,
            'objectId' => $entry->object_id,
            'objectType' => $entry->object_type,
            'confidenceScore' => $entry->confidence_score,
            'isAutomated' => (bool) $entry->is_automated,
            'timestamp' => $entry->created_at,
            'userId' => $entry->user_id,
            'oldData' => json_decode($entry->old_data, true),
            'newData' => json_decode($entry->new_data, true),
            'isRolledBack' => (bool) $entry->is_rolled_back
        );
    }
    
    /**
     * Calculate performance metrics
     */
    private function calculate_performance_metrics($actions) {
        return array(
            'averageProcessingTime' => $this->calculate_average_processing_time($actions),
            'throughput' => count($actions),
            'errorRate' => $this->calculate_error_rate($actions),
            'resourceUsage' => $this->estimate_resource_usage($actions)
        );
    }
    
    /**
     * Calculate quality metrics
     */
    private function calculate_quality_metrics($actions) {
        $confidence_scores = array_filter(array_column($actions, 'confidence_score'));
        
        return array(
            'averageConfidence' => count($confidence_scores) > 0 ? round(array_sum($confidence_scores) / count($confidence_scores), 2) : 0,
            'highConfidenceActions' => count(array_filter($confidence_scores, function($score) { return $score >= 90; })),
            'mediumConfidenceActions' => count(array_filter($confidence_scores, function($score) { return $score >= 70 && $score < 90; })),
            'lowConfidenceActions' => count(array_filter($confidence_scores, function($score) { return $score < 70; })),
            'qualityScore' => $this->calculate_overall_quality_score($actions)
        );
    }
    
    /**
     * Calculate audit performance metrics
     */
    private function calculate_audit_performance($audit_entries) {
        return array(
            'totalAutomatedActions' => count(array_filter($audit_entries, function($entry) { return $entry->is_automated; })),
            'rollbackRate' => $this->calculate_rollback_rate($audit_entries),
            'averageConfidence' => $this->calculate_average_audit_confidence($audit_entries),
            'actionDistribution' => $this->calculate_action_distribution($audit_entries)
        );
    }
    
    /**
     * Calculate audit quality metrics
     */
    private function calculate_audit_quality($audit_entries) {
        $automated_entries = array_filter($audit_entries, function($entry) { return $entry->is_automated; });
        $confidence_scores = array_filter(array_column($automated_entries, 'confidence_score'));
        
        return array(
            'automationQualityScore' => $this->calculate_automation_quality_score($automated_entries),
            'confidenceDistribution' => $this->calculate_confidence_distribution($confidence_scores),
            'rollbackAnalysis' => $this->analyze_rollbacks($audit_entries),
            'improvementSuggestions' => $this->generate_improvement_suggestions($audit_entries)
        );
    }
    
    /**
     * Send report to .NET Core API
     */
    private function send_report_to_api($report_data) {
        $api_url = $this->api_base_url . $this->report_endpoint;
        
        $response = wp_remote_post($api_url, array(
            'timeout' => $this->api_timeout,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ),
            'body' => wp_json_encode($report_data)
        ));
        
        if (is_wp_error($response)) {
            aysa_debug_log('Aysa Automation Report Error: ' . $response->get_error_message());
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        if ($response_code >= 200 && $response_code < 300) {
            aysa_debug_log('Aysa Automation Report sent successfully: ' . $response_body);
            return true;
        } else {
            aysa_debug_log('Aysa Automation Report failed with code ' . $response_code . ': ' . $response_body);
            return false;
        }
    }
    
    /**
     * Schedule automated reports
     */
    private function schedule_reports() {
        $frequency = get_option('aysa_automation_report_frequency', 'daily');
        
        switch ($frequency) {
            case 'hourly':
                wp_schedule_event(time(), 'hourly', 'aysa_send_automation_report');
                break;
            case 'daily':
                wp_schedule_event(time(), 'daily', 'aysa_send_automation_report');
                break;
            case 'weekly':
                wp_schedule_event(time(), 'weekly', 'aysa_send_automation_report');
                break;
            case 'monthly':
                wp_schedule_event(time(), 'monthly', 'aysa_send_automation_report');
                break;
        }
    }
    
    /**
     * Handle manual report request via AJAX
     */
    public function handle_manual_report_request() {
        check_ajax_referer('aysa_automation_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to send reports.'));
            return;
        }
        
        $this->send_scheduled_report();
        
        wp_send_json_success(array('message' => 'Automation report sent successfully.'));
    }
    
    /**
     * Helper methods for calculations
     */
    private function calculate_average_processing_time($actions) {
        return 1.5;
    }
    
    private function calculate_error_rate($actions) {
        $errors = count(array_filter($actions, function($action) { 
            return isset($action['success']) && !$action['success']; 
        }));
        return count($actions) > 0 ? round(($errors / count($actions)) * 100, 2) : 0;
    }
    
    private function estimate_resource_usage($actions) {
        return array(
            'memoryUsage' => count($actions) * 0.5,
            'cpuTime' => count($actions) * 0.1,
            'apiCalls' => count($actions)
        );
    }
    
    private function calculate_overall_quality_score($actions) {
        $confidence_scores = array_filter(array_column($actions, 'confidence_score'));
        $success_rate = $this->calculate_error_rate($actions);
        
        if (count($confidence_scores) === 0) return 0;
        
        $avg_confidence = array_sum($confidence_scores) / count($confidence_scores);
        return round(($avg_confidence + (100 - $success_rate)) / 2, 2);
    }
    
    private function calculate_rollback_rate($audit_entries) {
        $rolled_back = count(array_filter($audit_entries, function($entry) { return $entry->is_rolled_back; }));
        return count($audit_entries) > 0 ? round(($rolled_back / count($audit_entries)) * 100, 2) : 0;
    }
    
    private function calculate_average_audit_confidence($audit_entries) {
        $confidence_scores = array_filter(array_column($audit_entries, 'confidence_score'));
        return count($confidence_scores) > 0 ? round(array_sum($confidence_scores) / count($confidence_scores), 2) : 0;
    }
    
    private function calculate_action_distribution($audit_entries) {
        $distribution = array();
        foreach ($audit_entries as $entry) {
            $distribution[$entry->action_type] = ($distribution[$entry->action_type] ?? 0) + 1;
        }
        return $distribution;
    }
    
    private function calculate_automation_quality_score($automated_entries) {
        if (empty($automated_entries)) return 0;
        
        $confidence_scores = array_filter(array_column($automated_entries, 'confidence_score'));
        $rollback_rate = $this->calculate_rollback_rate($automated_entries);
        
        $avg_confidence = count($confidence_scores) > 0 ? array_sum($confidence_scores) / count($confidence_scores) : 0;
        return round(($avg_confidence * (100 - $rollback_rate)) / 100, 2);
    }
    
    private function calculate_confidence_distribution($confidence_scores) {
        return array(
            'high' => count(array_filter($confidence_scores, function($score) { return $score >= 90; })),
            'medium' => count(array_filter($confidence_scores, function($score) { return $score >= 70 && $score < 90; })),
            'low' => count(array_filter($confidence_scores, function($score) { return $score < 70; }))
        );
    }
    
    private function analyze_rollbacks($audit_entries) {
        $rollbacks = array_filter($audit_entries, function($entry) { return $entry->is_rolled_back; });
        
        return array(
            'totalRollbacks' => count($rollbacks),
            'rollbacksByType' => $this->calculate_action_distribution($rollbacks),
            'averageConfidenceOfRolledBack' => $this->calculate_average_audit_confidence($rollbacks)
        );
    }
    
    private function generate_improvement_suggestions($audit_entries) {
        $suggestions = array();
        
        $rollback_rate = $this->calculate_rollback_rate($audit_entries);
        if ($rollback_rate > 10) {
            $suggestions[] = 'Consider increasing confidence thresholds to reduce rollback rate';
        }
        
        $avg_confidence = $this->calculate_average_audit_confidence($audit_entries);
        if ($avg_confidence < 80) {
            $suggestions[] = 'Review and improve confidence scoring algorithms';
        }
        
        return $suggestions;
    }
    
    /**
     * Get detailed task information by task ID
     * Handles AJAX request for task detail modal
     */
    public function get_task_details_by_id($task_id) {
        $task_details = array(
            'task_id' => $task_id,
            'title' => '',
            'status' => 'pending',
            'progress' => 0,
            'type' => 'manual',
            'estimated_time' => '',
            'completed_steps' => 0,
            'total_steps' => 1,
            'steps' => array(),
            'metrics' => array(),
            'dependencies' => array(),
            'troubleshooting' => '',
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        );
        
        global $wpdb;
        $audit_table = $wpdb->prefix . 'aysa_audit_log';
        
        $task_data = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$audit_table} WHERE id = %s OR object_id = %s LIMIT 1",
            $task_id,
            $task_id
        ));
        
        if ($task_data) {
            $task_details['title'] = $this->format_task_title($task_data->action_type);
            $task_details['type'] = $task_data->is_automated ? 'automated' : 'manual';
            $task_details['progress'] = $this->calculate_task_progress($task_data);
            $task_details['status'] = $this->determine_task_status($task_data);
            $task_details['steps'] = $this->generate_task_steps($task_data);
            $task_details['metrics'] = $this->calculate_task_metrics($task_data);
            $task_details['dependencies'] = $this->get_task_dependencies($task_data);
            $task_details['troubleshooting'] = $this->get_troubleshooting_info($task_data);
            $task_details['estimated_time'] = $this->estimate_completion_time($task_data);
        }
        
        return $task_details;
    }
    
    /**
     * Handle AJAX request for task details
     */
    public function handle_get_task_details() {
        check_ajax_referer('aysa_task_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to view task details.'));
            return;
        }
        
        $task_id = sanitize_text_field($_POST['task_id']);
        
        if (empty($task_id)) {
            wp_send_json_error(array('message' => 'Task ID is required.'));
            return;
        }
        
        $task_details = $this->get_task_details_by_id($task_id);
        
        wp_send_json_success($task_details);
    }
    
    /**
     * Helper methods for task detail processing
     */
    private function format_task_title($action_type) {
        $titles = array(
            'image_optimization' => 'Optimize Images for SEO',
            'redirect_creation' => 'Create SEO Redirects',
            'meta_generation' => 'Generate Meta Tags',
            'link_building' => 'Build Quality Backlinks',
            'content_optimization' => 'Optimize Content for Keywords'
        );
        
        return $titles[$action_type] ?? ucwords(str_replace('_', ' ', $action_type));
    }
    
    private function calculate_task_progress($task_data) {
        if ($task_data->is_rolled_back) {
            return 0;
        }
        
        $confidence = $task_data->confidence_score ?? 0;
        
        if ($confidence >= 0.9) {
            return 100;
        } elseif ($confidence >= 0.7) {
            return 75;
        } elseif ($confidence >= 0.5) {
            return 50;
        } elseif ($confidence > 0) {
            return 25;
        }
        
        return 0;
    }
    
    private function determine_task_status($task_data) {
        if ($task_data->is_rolled_back) {
            return 'failed';
        }
        
        $progress = $this->calculate_task_progress($task_data);
        
        if ($progress >= 100) {
            return 'completed';
        } elseif ($progress > 0) {
            return 'in-progress';
        }
        
        return 'pending';
    }
    
    private function generate_task_steps($task_data) {
        $base_steps = array(
            array('text' => 'Initialize task', 'status' => 'completed'),
            array('text' => 'Analyze requirements', 'status' => 'completed'),
            array('text' => 'Execute primary action', 'status' => 'current'),
            array('text' => 'Validate results', 'status' => 'pending'),
            array('text' => 'Complete task', 'status' => 'pending')
        );
        
        $progress = $this->calculate_task_progress($task_data);
        $completed_steps = floor($progress / 20);
        
        for ($i = 0; $i < count($base_steps); $i++) {
            if ($i < $completed_steps) {
                $base_steps[$i]['status'] = 'completed';
            } elseif ($i === $completed_steps && $progress < 100) {
                $base_steps[$i]['status'] = 'current';
            } else {
                $base_steps[$i]['status'] = 'pending';
            }
        }
        
        return $base_steps;
    }
    
    private function calculate_task_metrics($task_data) {
        return array(
            'confidence' => round(($task_data->confidence_score ?? 0) * 100) . '%',
            'attempts' => '1',
            'success_rate' => $task_data->is_rolled_back ? '0%' : '100%',
            'time_spent' => '1.2h'
        );
    }
    
    private function get_task_dependencies($task_data) {
        $dependencies = array(
            'image_optimization' => array('Images uploaded', 'Alt text requirements defined'),
            'redirect_creation' => array('URL mapping completed', 'Redirect rules defined'),
            'meta_generation' => array('Content analysis completed', 'Target keywords identified'),
            'link_building' => array('Target sites identified', 'Outreach templates ready'),
            'content_optimization' => array('Keyword research completed', 'Content audit finished')
        );
        
        return $dependencies[$task_data->action_type] ?? array('No specific dependencies');
    }
    
    private function get_troubleshooting_info($task_data) {
        $troubleshooting = array(
            'image_optimization' => 'Ensure images are in supported formats (JPG, PNG, WebP). Check file permissions.',
            'redirect_creation' => 'Verify source URLs exist and target URLs are valid. Check for redirect loops.',
            'meta_generation' => 'Ensure content has sufficient text for analysis. Check character limits.',
            'link_building' => 'Verify target sites accept guest posts. Check domain authority requirements.',
            'content_optimization' => 'Ensure content meets minimum word count. Check keyword density guidelines.'
        );
        
        return $troubleshooting[$task_data->action_type] ?? 'No specific troubleshooting information available.';
    }
    
    private function estimate_completion_time($task_data) {
        $progress = $this->calculate_task_progress($task_data);
        
        if ($progress >= 100) {
            return 'Completed';
        }
        
        $remaining_percentage = 100 - $progress;
        $estimated_hours = round(($remaining_percentage / 100) * 2, 1);
        
        if ($estimated_hours < 1) {
            return round($estimated_hours * 60) . ' minutes remaining';
        }
        
        return $estimated_hours . ' hours remaining';
    }
}
