<?php
/**
 * Activity Report Management Class
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.6 Email report
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * VMPFence Activity Report Class
 *
 * @since 1.0.0
 */
class VMPFence_Activity_Report {

    /**
     * Generate comprehensive activity report
     *
     * @since 1.0.0
     * @param array $args Report arguments
     * @return array
     */
    public static function generate_report($args = array()) {
        $defaults = array(
            'period' => '30_days',
            'include_sections' => array(
                'overview',
                'security_threats',
                'scan_results',
                'login_activity',
                'traffic_analysis',
                'performance_metrics',
                'configuration_changes',
                'recommendations'
            )
        );

        $args = wp_parse_args($args, $defaults);
        $period_info = self::get_period_info($args['period']);
        
        $report = array(
            'generated_at' => current_time('timestamp'),
            'period' => $period_info,
            'site_info' => self::get_site_info(),
            'sections' => array()
        );

        // Generate each requested section
        foreach ($args['include_sections'] as $section) {
            $method = 'get_' . $section . '_section';
            if (method_exists(__CLASS__, $method)) {
                $report['sections'][$section] = self::$method($period_info);
            }
        }

        return $report;
    }

    /**
     * Get overview section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_overview_section($period_info) {
        global $wpdb;

        $overview = array(
            'title' => __('Security Overview', 'vmpfence-security'),
            'summary' => array(),
            'key_metrics' => array(),
            'status' => 'healthy'
        );

        // Get threat counts
        $threats_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_THREATS);
        $threat_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM `{$threats_table}` WHERE first_seen >= %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ));

        // Get blocked IPs
        $blocked_ips_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BLOCKED_IPS);
        $blocked_ip_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM `{$blocked_ips_table}` WHERE blocked_at >= %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ));

        // Get scan count
        $scans_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SCANS);
        $scan_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM `{$scans_table}` WHERE start_time >= %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ));

        // Get failed login attempts
        $audit_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_AUDIT_LOG);
        $failed_logins = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM `{$audit_table}` WHERE event_type = %s AND time >= %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            VMPFence_Constants::EVENT_LOGIN_FAILURE,
            $period_info['start_time']
        ));

        $overview['key_metrics'] = array(
            'threats_detected' => (int) $threat_count,
            'ips_blocked' => (int) $blocked_ip_count,
            'scans_performed' => (int) $scan_count,
            'failed_login_attempts' => (int) $failed_logins
        );

        // Determine overall status
        if ($threat_count > 10 || $failed_logins > 100) {
            $overview['status'] = 'warning';
        }
        if ($threat_count > 50 || $failed_logins > 500) {
            $overview['status'] = 'critical';
        }

        $overview['summary'] = array(
            /* translators: %d: number of security threats */
            sprintf(__('%d security threats detected and mitigated', 'vmpfence-security'), $threat_count),
            /* translators: %d: number of IP addresses */
            sprintf(__('%d IP addresses blocked for suspicious activity', 'vmpfence-security'), $blocked_ip_count),
            /* translators: %d: number of security scans */
            sprintf(__('%d security scans completed', 'vmpfence-security'), $scan_count),
            /* translators: %d: number of failed login attempts */
            sprintf(__('%d failed login attempts blocked', 'vmpfence-security'), $failed_logins)
        );

        return $overview;
    }

    /**
     * Get security threats section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_security_threats_section($period_info) {
        global $wpdb;

        $section = array(
            'title' => __('Security Threats', 'vmpfence-security'),
            'threats_by_type' => array(),
            'recent_threats' => array(),
            'top_threat_sources' => array()
        );

        $threats_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_THREATS);

        // Get threats by type
        $threats_by_type = $wpdb->get_results($wpdb->prepare(
            "SELECT threat_type, COUNT(*) as count FROM `{$threats_table}` WHERE first_seen >= %d GROUP BY threat_type ORDER BY count DESC", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ), ARRAY_A);

        $section['threats_by_type'] = $threats_by_type;

        // Get recent threats
        $recent_threats = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM `{$threats_table}` WHERE first_seen >= %d ORDER BY first_seen DESC LIMIT 10", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ), ARRAY_A);

        foreach ($recent_threats as &$threat) {
            $threat['first_seen_formatted'] = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $threat['first_seen']);
            // source_ip is varbinary - convert to readable format (supports IPv4 and IPv6)
            if (is_string($threat['source_ip']) && (strlen($threat['source_ip']) === 4 || strlen($threat['source_ip']) === 16)) {
                $threat['ip_formatted'] = @inet_ntop($threat['source_ip']) ?: $threat['source_ip'];
            } else {
                $threat['ip_formatted'] = $threat['source_ip'];
            }
        }

        $section['recent_threats'] = $recent_threats;

        // Get top threat sources
        $top_sources = $wpdb->get_results($wpdb->prepare(
            "SELECT source_ip, COUNT(*) as count FROM `{$threats_table}` WHERE first_seen >= %d GROUP BY source_ip ORDER BY count DESC LIMIT 10", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ), ARRAY_A);

        foreach ($top_sources as &$source) {
            // source_ip is varbinary - convert to readable format (supports IPv4 and IPv6)
            if (is_string($source['source_ip']) && (strlen($source['source_ip']) === 4 || strlen($source['source_ip']) === 16)) {
                $source['ip_formatted'] = @inet_ntop($source['source_ip']) ?: $source['source_ip'];
            } else {
                $source['ip_formatted'] = $source['source_ip'];
            }
            $source['country'] = VMPFence_Utils::geolocate_ip($source['ip_formatted']);
        }

        $section['top_threat_sources'] = $top_sources;

        return $section;
    }

    /**
     * Get scan results section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_scan_results_section($period_info) {
        global $wpdb;

        $section = array(
            'title' => __('Scan Results', 'vmpfence-security'),
            'scan_summary' => array(),
            'recent_scans' => array(),
            'scan_performance' => array()
        );

        $scans_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SCANS);

        // Get scan summary
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $scan_stats = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                COUNT(*) as total_scans,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_scans,
                SUM(files_scanned) as total_files_scanned,
                SUM(threats_found) as total_threats_found,
                AVG(duration) as avg_duration
            FROM `{$scans_table}`
            WHERE start_time >= %d",
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $section['scan_summary'] = array(
            'total_scans' => (int) $scan_stats['total_scans'],
            'completed_scans' => (int) $scan_stats['completed_scans'],
            'files_scanned' => (int) $scan_stats['total_files_scanned'],
            'threats_found' => (int) $scan_stats['total_threats_found'],
            'average_duration' => round($scan_stats['avg_duration'], 2)
        );

        // Get recent scans
        $recent_scans = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM `{$scans_table}` WHERE start_time >= %d ORDER BY start_time DESC LIMIT 10", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        ), ARRAY_A);

        foreach ($recent_scans as &$scan) {
            $scan['start_time_formatted'] = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $scan['start_time']);
            $scan['duration_formatted'] = self::format_duration($scan['duration']);
        }

        $section['recent_scans'] = $recent_scans;

        // Get scan performance over time
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $performance_data = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                DATE(FROM_UNIXTIME(start_time)) as date,
                COUNT(*) as scans_count,
                AVG(duration) as avg_duration,
                SUM(threats_found) as threats_found
            FROM `{$scans_table}`
            WHERE start_time >= %d 
            GROUP BY DATE(FROM_UNIXTIME(start_time))
            ORDER BY date",
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $section['scan_performance'] = $performance_data;

        return $section;
    }

    /**
     * Get login activity section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_login_activity_section($period_info) {
        global $wpdb;

        $section = array(
            'title' => __('Login Activity', 'vmpfence-security'),
            'login_summary' => array(),
            'failed_login_trends' => array(),
            'top_attack_sources' => array(),
            'brute_force_attempts' => array()
        );

        $audit_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_AUDIT_LOG);

        // Get login summary
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $login_stats = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                SUM(CASE WHEN event_type = %s THEN 1 ELSE 0 END) as successful_logins,
                SUM(CASE WHEN event_type = %s THEN 1 ELSE 0 END) as failed_logins,
                SUM(CASE WHEN event_type = %s THEN 1 ELSE 0 END) as blocked_logins
            FROM `{$audit_table}`
            WHERE time >= %d",
            VMPFence_Constants::EVENT_LOGIN_SUCCESS,
            VMPFence_Constants::EVENT_LOGIN_FAILURE,
            VMPFence_Constants::EVENT_LOGIN_BLOCKED,
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $section['login_summary'] = array(
            'successful_logins' => (int) $login_stats['successful_logins'],
            'failed_logins' => (int) $login_stats['failed_logins'],
            'blocked_logins' => (int) $login_stats['blocked_logins']
        );

        // Get failed login trends
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $failed_trends = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                DATE(FROM_UNIXTIME(time)) as date,
                COUNT(*) as failed_count
            FROM `{$audit_table}`
            WHERE event_type = %s AND time >= %d
            GROUP BY DATE(FROM_UNIXTIME(time))
            ORDER BY date",
            VMPFence_Constants::EVENT_LOGIN_FAILURE,
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $section['failed_login_trends'] = $failed_trends;

        // Get top attack sources
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $attack_sources = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                source_ip,
                COUNT(*) as attempt_count
            FROM `{$audit_table}`
            WHERE event_type IN (%s, %s) AND time >= %d
            GROUP BY source_ip
            ORDER BY attempt_count DESC
            LIMIT 10",
            VMPFence_Constants::EVENT_LOGIN_FAILURE,
            VMPFence_Constants::EVENT_LOGIN_BLOCKED,
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        foreach ($attack_sources as &$source) {
            // source_ip is varbinary - convert to readable format (supports IPv4 and IPv6)
            if (is_string($source['source_ip']) && (strlen($source['source_ip']) === 4 || strlen($source['source_ip']) === 16)) {
                $source['ip_formatted'] = @inet_ntop($source['source_ip']) ?: $source['source_ip'];
            } else {
                $source['ip_formatted'] = $source['source_ip'];
            }
            $source['country'] = VMPFence_Utils::geolocate_ip($source['ip_formatted']);
        }

        $section['top_attack_sources'] = $attack_sources;

        return $section;
    }

    /**
     * Get traffic analysis section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_traffic_analysis_section($period_info) {
        global $wpdb;

        $section = array(
            'title' => __('Traffic Analysis', 'vmpfence-security'),
            'traffic_summary' => array(),
            'top_countries' => array(),
            'suspicious_patterns' => array(),
            'bandwidth_usage' => array()
        );

        $traffic_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_TRAFFIC_LOG);

        // Get traffic summary
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $traffic_stats = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                COUNT(*) as total_requests,
                COUNT(DISTINCT source_ip) as unique_visitors,
                SUM(CASE WHEN status_code >= 400 THEN 1 ELSE 0 END) as error_requests,
                AVG(response_time) as avg_response_time
            FROM `{$traffic_table}`
            WHERE timestamp >= %d",
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $section['traffic_summary'] = array(
            'total_requests' => (int) $traffic_stats['total_requests'],
            'unique_visitors' => (int) $traffic_stats['unique_visitors'],
            'error_requests' => (int) $traffic_stats['error_requests'],
            'avg_response_time' => round($traffic_stats['avg_response_time'], 2)
        );

        // Get top countries
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $top_countries = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                country,
                COUNT(*) as request_count,
                COUNT(DISTINCT source_ip) as unique_ips
            FROM `{$traffic_table}`
            WHERE timestamp >= %d AND country != ''
            GROUP BY country
            ORDER BY request_count DESC
            LIMIT 10",
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $section['top_countries'] = $top_countries;

        // Get suspicious patterns
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $suspicious_patterns = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                source_ip,
                COUNT(*) as request_count,
                COUNT(DISTINCT url) as unique_urls,
                SUM(CASE WHEN status_code = 404 THEN 1 ELSE 0 END) as not_found_requests
            FROM `{$traffic_table}`
            WHERE timestamp >= %d
            GROUP BY source_ip
            HAVING request_count > 1000 OR not_found_requests > 50
            ORDER BY request_count DESC
            LIMIT 10",
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        foreach ($suspicious_patterns as &$pattern) {
            // source_ip is varbinary - convert to readable format (supports IPv4 and IPv6)
            if (is_string($pattern['source_ip']) && (strlen($pattern['source_ip']) === 4 || strlen($pattern['source_ip']) === 16)) {
                $pattern['ip_formatted'] = @inet_ntop($pattern['source_ip']) ?: $pattern['source_ip'];
            } else {
                $pattern['ip_formatted'] = $pattern['source_ip'];
            }
        }

        $section['suspicious_patterns'] = $suspicious_patterns;

        return $section;
    }

    /**
     * Get performance metrics section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_performance_metrics_section($period_info) {
        global $wpdb;

        $section = array(
            'title' => __('Performance Metrics', 'vmpfence-security'),
            'plugin_performance' => array(),
            'database_health' => array(),
            'cache_statistics' => array(),
            'resource_usage' => array()
        );

        // Get plugin performance metrics
        $section['plugin_performance'] = array(
            'average_scan_time' => self::get_average_scan_time($period_info),
            'waf_processing_time' => self::get_waf_processing_time($period_info),
            'database_queries' => self::get_database_query_count($period_info),
            'memory_usage' => self::get_memory_usage()
        );

        // Get database health
        $section['database_health'] = self::get_database_health();

        // Get cache statistics
        $section['cache_statistics'] = array(
            'cache_hits' => VMPFence_Config::get('cache_hits', 0),
            'cache_misses' => VMPFence_Config::get('cache_misses', 0),
            'cache_size' => self::get_cache_size(),
            'cache_efficiency' => self::calculate_cache_efficiency()
        );

        return $section;
    }

    /**
     * Get configuration changes section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_configuration_changes_section($period_info) {
        global $wpdb;

        $section = array(
            'title' => __('Configuration Changes', 'vmpfence-security'),
            'recent_changes' => array(),
            'security_settings' => array(),
            'plugin_updates' => array()
        );

        $audit_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_AUDIT_LOG);

        // Get recent configuration changes
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $config_changes = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM `{$audit_table}`
            WHERE event_type = %s AND time >= %d 
            ORDER BY time DESC 
            LIMIT 20",
            VMPFence_Constants::EVENT_CONFIG_CHANGED,
            $period_info['start_time']
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        foreach ($config_changes as &$change) {
            $change['time_formatted'] = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $change['time']);
            $change['additional_info'] = maybe_unserialize($change['additional_info']);
        }

        $section['recent_changes'] = $config_changes;

        // Get current security settings summary
        $section['security_settings'] = array(
            'waf_enabled' => VMPFence_Config::get('waf_enabled', false),
            'login_protection' => VMPFence_Config::get('login_protection_enabled', false),
            'scan_schedule' => VMPFence_Config::get('scan_schedule', 'daily'),
            'audit_logging' => VMPFence_Config::get('enable_audit_log', false),
            'two_factor_enabled' => VMPFence_Config::get('two_factor_enabled', false)
        );

        return $section;
    }

    /**
     * Get recommendations section
     *
     * @since 1.0.0
     * @param array $period_info Period information
     * @return array
     */
    private static function get_recommendations_section($period_info) {
        $section = array(
            'title' => __('Security Recommendations', 'vmpfence-security'),
            'high_priority' => array(),
            'medium_priority' => array(),
            'low_priority' => array()
        );

        $recommendations = self::analyze_security_posture($period_info);

        foreach ($recommendations as $rec) {
            $section[$rec['priority'] . '_priority'][] = $rec;
        }

        return $section;
    }

    /**
     * Export report to PDF
     *
     * @since 1.0.0
     * @param array $report Report data
     * @return string PDF file path
     */
    public static function export_to_pdf($report) {
        // This would require a PDF library like TCPDF or FPDF
        // For now, return a placeholder path
        $upload_dir = wp_upload_dir();
        $filename = 'vmpfence-report-' . gmdate('Y-m-d-H-i-s') . '.pdf';
        $filepath = $upload_dir['path'] . '/' . $filename;

        // TODO: Implement PDF generation
        file_put_contents($filepath, 'PDF generation not yet implemented');

        return $filepath;
    }

    /**
     * Export report to HTML
     *
     * @since 1.0.0
     * @param array $report Report data
     * @return string HTML content
     */
    public static function export_to_html($report) {
        // Read CSS file content for embedding in standalone HTML
        $css_file = plugin_dir_path(dirname(__FILE__)) . 'admin/assets/css/report-export.css';
        $css_content = '';
        
        if (file_exists($css_file)) {
            $css_content = file_get_contents($css_file);
        }
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>VMP Fence Security Report</title>
            <?php if (!empty($css_content)): ?>
            <style><?php echo $css_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static CSS file content ?></style>
            <?php endif; ?>
        </head>
        <body>
            <div class="header">
                <h1>VMP Fence Security Report</h1>
                <p><strong>Site:</strong> <?php echo esc_html($report['site_info']['site_name']); ?></p>
                <p><strong>Generated:</strong> <?php echo esc_html( date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $report['generated_at']) ); ?></p>
                <p><strong>Period:</strong> <?php echo esc_html($report['period']['label']); ?></p>
            </div>

            <?php foreach ($report['sections'] as $section_key => $section): ?>
                <div class="section">
                    <h2><?php echo esc_html($section['title']); ?></h2>
                    
                    <?php if ($section_key === 'overview'): ?>
                        <div class="status-<?php echo esc_attr($section['status']); ?>">
                            <h3>Overall Status: <?php echo esc_html(ucfirst($section['status'])); ?></h3>
                        </div>
                        
                        <div class="metrics">
                            <?php foreach ($section['key_metrics'] as $metric => $value): ?>
                                <div class="metric">
                                    <strong><?php echo esc_html(ucwords(str_replace('_', ' ', $metric))); ?>:</strong><br>
                                    <?php echo esc_html(number_format($value)); ?>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <ul>
                            <?php foreach ($section['summary'] as $item): ?>
                                <li><?php echo esc_html($item); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>

                    <?php if (isset($section['threats_by_type']) && !empty($section['threats_by_type'])): ?>
                        <h3>Threats by Type</h3>
                        <table>
                            <tr><th>Threat Type</th><th>Count</th></tr>
                            <?php foreach ($section['threats_by_type'] as $threat): ?>
                                <tr>
                                    <td><?php echo esc_html($threat['threat_type']); ?></td>
                                    <td><?php echo esc_html($threat['count']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </table>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Schedule automated reports
     *
     * @since 1.0.0
     * @param string $frequency Report frequency (daily, weekly, monthly)
     * @param array $recipients Email recipients
     * @return bool
     */
    public static function schedule_automated_report($frequency, $recipients) {
        $hook = 'vmpfence_send_automated_report';
        
        // Clear existing schedule
        wp_clear_scheduled_hook($hook);

        // Schedule new report
        $schedules = array(
            'daily' => 'daily',
            'weekly' => 'weekly',
            'monthly' => 'monthly'
        );

        if (isset($schedules[$frequency])) {
            $scheduled = wp_schedule_event(time(), $schedules[$frequency], $hook, array($recipients));
            
            if ($scheduled) {
                VMPFence_Config::set('automated_reports_enabled', true);
                VMPFence_Config::set('automated_reports_frequency', $frequency);
                VMPFence_Config::set('automated_reports_recipients', $recipients);
            }

            return $scheduled;
        }

        return false;
    }

    /**
     * Send automated report via email
     *
     * @since 1.0.0
     * @param array $recipients Email recipients
     * @return bool
     */
    public static function send_automated_report($recipients) {
        $report = self::generate_report();
        $html_content = self::export_to_html($report);

        // Send via centralized Email Service (API → branded template)
        $context = array(
            'html_content'  => $html_content,
            'report_period' => isset($report['period']['label']) ? $report['period']['label'] : '',
            'report_date'   => current_time('Y-m-d H:i:s'),
        );

        $result = VMPFence_Email_Service::send_alert('activity_report', $context, $recipients);

        return $result['success'];
    }

    /**
     * Helper methods
     */
    
    private static function get_period_info($period) {
        $end_time = current_time('timestamp');
        
        switch ($period) {
            case '7_days':
                return array(
                    'start_time' => $end_time - (7 * 86400),
                    'end_time' => $end_time,
                    'label' => __('Last 7 Days', 'vmpfence-security'),
                    'days' => 7
                );
                
            case '30_days':
                return array(
                    'start_time' => $end_time - (30 * 86400),
                    'end_time' => $end_time,
                    'label' => __('Last 30 Days', 'vmpfence-security'),
                    'days' => 30
                );
                
            case '90_days':
                return array(
                    'start_time' => $end_time - (90 * 86400),
                    'end_time' => $end_time,
                    'label' => __('Last 90 Days', 'vmpfence-security'),
                    'days' => 90
                );
                
            default:
                return array(
                    'start_time' => $end_time - (30 * 86400),
                    'end_time' => $end_time,
                    'label' => __('Last 30 Days', 'vmpfence-security'),
                    'days' => 30
                );
        }
    }

    private static function get_site_info() {
        return array(
            'site_name' => get_bloginfo('name'),
            'site_url' => get_site_url(),
            'wp_version' => get_bloginfo('version'),
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'php_version' => PHP_VERSION,
            'server_software' => sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'))
        );
    }

    private static function format_duration($seconds) {
        if ($seconds < 60) {
            /* translators: %d: number of seconds */
            return sprintf(__('%d seconds', 'vmpfence-security'), $seconds);
        } elseif ($seconds < 3600) {
            /* translators: %d: number of minutes */
            return sprintf(__('%d minutes', 'vmpfence-security'), floor($seconds / 60));
        } else {
            /* translators: %1$d: number of hours, %2$d: number of minutes */
            return sprintf(__('%1$d hours, %2$d minutes', 'vmpfence-security'), floor($seconds / 3600), floor(($seconds % 3600) / 60));
        }
    }

    private static function get_average_scan_time($period_info) {
        global $wpdb;
        $scans_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SCANS);
        
        return $wpdb->get_var($wpdb->prepare(
            "SELECT AVG(duration) FROM `{$scans_table}` WHERE start_time >= %d AND status = 'completed'", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $period_info['start_time']
        )) ?: 0;
    }

    private static function get_waf_processing_time($period_info) {
        // This would be tracked in WAF logs
        return VMPFence_Config::get('avg_waf_processing_time', 0);
    }

    private static function get_database_query_count($period_info) {
        return VMPFence_Config::get('total_db_queries', 0);
    }

    private static function get_memory_usage() {
        return array(
            'current' => memory_get_usage(true),
            'peak' => memory_get_peak_usage(true),
            'limit' => ini_get('memory_limit')
        );
    }

    private static function get_database_health() {
        global $wpdb;
        
        $health = array(
            'table_status' => 'healthy',
            'total_size' => 0,
            'fragmentation' => 'low'
        );

        // Check table sizes and status
        $tables = array(
            VMPFence_Constants::TABLE_SCANS,
            VMPFence_Constants::TABLE_THREATS,
            VMPFence_Constants::TABLE_AUDIT_LOG,
            VMPFence_Constants::TABLE_TRAFFIC_LOG
        );

        foreach ($tables as $table) {
            $table_name = VMPFence_Constants::get_table_name($table);
            $size = $wpdb->get_var($wpdb->prepare(
                "SELECT ROUND(((data_length + index_length) / 1024 / 1024), 2) FROM information_schema.TABLES WHERE table_schema = DATABASE() AND table_name = %s",
                $table_name
            ));
            $health['total_size'] += $size;
        }

        return $health;
    }

    private static function get_cache_size() {
        // Implementation depends on caching mechanism
        return 0;
    }

    private static function calculate_cache_efficiency() {
        $hits = VMPFence_Config::get('cache_hits', 0);
        $misses = VMPFence_Config::get('cache_misses', 0);
        $total = $hits + $misses;
        
        return $total > 0 ? ($hits / $total) * 100 : 0;
    }

    private static function analyze_security_posture($period_info) {
        $recommendations = array();

        // Check if WAF is enabled
        if (!VMPFence_Config::get('waf_enabled')) {
            $recommendations[] = array(
                'priority' => 'high',
                'title' => __('Enable Web Application Firewall', 'vmpfence-security'),
                'description' => __('WAF protection is disabled. Enable it to block malicious requests.', 'vmpfence-security'),
                'action' => 'enable_waf'
            );
        }

        // Check scan frequency
        $scan_schedule = VMPFence_Config::get('scan_schedule');
        if ($scan_schedule === 'never') {
            $recommendations[] = array(
                'priority' => 'high',
                'title' => __('Enable Scheduled Scans', 'vmpfence-security'),
                'description' => __('No scheduled scans are configured. Enable daily or weekly scans.', 'vmpfence-security'),
                'action' => 'configure_scans'
            );
        }

        // Check for recent threats
        global $wpdb;
        $threats_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_THREATS);
        $recent_threats = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM `{$threats_table}` WHERE first_seen >= %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            time() - (7 * 86400)
        ));

        if ($recent_threats > 10) {
            $recommendations[] = array(
                'priority' => 'medium',
                'title' => __('High Threat Activity Detected', 'vmpfence-security'),
                /* translators: %d: number of threats detected */
                'description' => sprintf(__('%d threats detected in the last 7 days. Review security settings.', 'vmpfence-security'), $recent_threats),
                'action' => 'review_threats'
            );
        }

        return $recommendations;
    }
}
