<?php
/**
 * Sentinel Digest Reports Class
 * 
 * Handles generation and sending of daily and weekly digest reports.
 */

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

class Sentinel_Digest_Reports {
    
    /**
     * Constructor
     */
    public function __construct() {
        // Constructor
    }
    
    /**
     * Initialize digest report hooks
     */
    public static function init() {
        // Add cron hooks for digest reports
        add_action('sentinel_daily_digest', array(__CLASS__, 'process_daily_digests'));
        add_action('sentinel_weekly_digest', array(__CLASS__, 'process_weekly_digests'));
    }
    
    /**
     * Check if digest notifications are enabled
     * 
     * @param string $digest_type Type of digest (daily_summary, daily_error, daily_user, weekly_health, weekly_performance, weekly_security)
     * @return bool True if enabled, false otherwise
     */
    public static function is_digest_enabled($digest_type) {
        $settings = get_option('sentinel_log_management', array());
        $setting_key = 'sentinel_email_' . $digest_type;
        
        return !empty($settings[$setting_key]);
    }
    
    /**
     * Get daily statistics for the past 24 hours
     * 
     * @return array Statistics data
     */
    public static function get_daily_statistics() {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // For testing, let's use today instead of yesterday to see all recent events
        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');
        
        // Debug: Log the date range being used
        error_log('[Sentinel Debug] Daily statistics date range: ' . $today_start . ' to ' . $today_end);
        
        // Debug: Get total events in database
        $total_all_events = $wpdb->get_var("SELECT COUNT(*) FROM $table");
        error_log('[Sentinel Debug] Total events in database: ' . $total_all_events);
        
        // Total events
        $total_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s",
            $today_start, $today_end
        ));
        
        // Events by category
        $events_by_category = $wpdb->get_results($wpdb->prepare(
            "SELECT category, COUNT(*) as count FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY category 
             ORDER BY count DESC",
            $today_start, $today_end
        ));
        
        // Events by priority
        $events_by_priority = $wpdb->get_results($wpdb->prepare(
            "SELECT priority, COUNT(*) as count FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY priority 
             ORDER BY count DESC",
            $today_start, $today_end
        ));
        
        // Top events
        $top_events = $wpdb->get_results($wpdb->prepare(
            "SELECT event_key, COUNT(*) as count FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY event_key 
             ORDER BY count DESC 
             LIMIT 10",
            $today_start, $today_end
        ));
        
        // Ensure arrays before returning
        $events_by_category = is_array($events_by_category) ? $events_by_category : array();
        $events_by_priority = is_array($events_by_priority) ? $events_by_priority : array();
        $top_events = is_array($top_events) ? $top_events : array();
        
        // Active users
        $active_users = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT user_id) FROM $table 
             WHERE created_at BETWEEN %s AND %s AND user_id > 0",
            $today_start, $today_end
        ));
        
        return array(
            'period' => 'daily',
            'date_range' => array(
                'start' => $today_start,
                'end' => $today_end
            ),
            'total_events' => intval($total_events),
            'active_users' => intval($active_users),
            'events_by_category' => $events_by_category,
            'events_by_priority' => $events_by_priority,
            'top_events' => $top_events
        );
    }
    
    /**
     * Get weekly statistics for the past 7 days
     * 
     * @return array Statistics data
     */
    public static function get_weekly_statistics() {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // For testing, let's use past 7 days including today
        $week_start = date('Y-m-d 00:00:00', strtotime('-7 days'));
        $week_end = date('Y-m-d 23:59:59'); // Include today
        
        // Debug: Log the date range being used
        error_log('[Sentinel Debug] Weekly statistics date range: ' . $week_start . ' to ' . $week_end);
        
        // Debug: Get total events in database
        $total_all_events = $wpdb->get_var("SELECT COUNT(*) FROM $table");
        error_log('[Sentinel Debug] Total events in database: ' . $total_all_events);
        
        // Total events
        $total_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s",
            $week_start, $week_end
        ));
        
        // Events by category
        $events_by_category = $wpdb->get_results($wpdb->prepare(
            "SELECT category, COUNT(*) as count FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY category 
             ORDER BY count DESC",
            $week_start, $week_end
        ));
        
        // Events by priority
        $events_by_priority = $wpdb->get_results($wpdb->prepare(
            "SELECT priority, COUNT(*) as count FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY priority 
             ORDER BY count DESC",
            $week_start, $week_end
        ));
        
        // Top events
        $top_events = $wpdb->get_results($wpdb->prepare(
            "SELECT event_key, COUNT(*) as count FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY event_key 
             ORDER BY count DESC 
             LIMIT 10",
            $week_start, $week_end
        ));
        
        // Ensure arrays before returning
        $events_by_category = is_array($events_by_category) ? $events_by_category : array();
        $events_by_priority = is_array($events_by_priority) ? $events_by_priority : array();
        $top_events = is_array($top_events) ? $top_events : array();
        
        // Active users
        $active_users = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT user_id) FROM $table 
             WHERE created_at BETWEEN %s AND %s AND user_id > 0",
            $week_start, $week_end
        ));
        
        // Daily breakdown for the week
        $daily_breakdown = array();
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $start = $date . ' 00:00:00';
            $end = $date . ' 23:59:59';
            $count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s",
                $start, $end
            ));
            $daily_breakdown[] = array(
                'date' => $date,
                'count' => intval($count)
            );
        }
        
        return array(
            'period' => 'weekly',
            'date_range' => array(
                'start' => $week_start,
                'end' => $week_end
            ),
            'total_events' => intval($total_events),
            'active_users' => intval($active_users),
            'events_by_category' => $events_by_category,
            'events_by_priority' => $events_by_priority,
            'top_events' => $top_events,
            'daily_breakdown' => $daily_breakdown
        );
    }
    
    /**
     * Get error events for the specified period
     * 
     * @param string $period 'daily' or 'weekly'
     * @return array Error events data
     */
    public static function get_error_events($period = 'daily') {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        if ($period === 'daily') {
            $start = date('Y-m-d 00:00:00', strtotime('-1 day'));
            $end = date('Y-m-d 23:59:59', strtotime('-1 day'));
        } else {
            $start = date('Y-m-d 00:00:00', strtotime('-7 days'));
            $end = date('Y-m-d 23:59:59', strtotime('-1 day'));
        }
        
        // Get high and critical events
        $error_events = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (priority IN ('high', 'critical') OR event_key LIKE %s OR event_key LIKE %s)
             ORDER BY created_at DESC 
             LIMIT 50",
            $start, $end, '%error%', '%failed%'
        ));
        
        // Ensure $error_events is an array before counting
        $error_events = is_array($error_events) ? $error_events : array();
        
        return array(
            'period' => $period,
            'date_range' => array(
                'start' => $start,
                'end' => $end
            ),
            'error_events' => $error_events,
            'total_errors' => count($error_events)
        );
    }
    
    /**
     * Get user activity for the specified period
     * 
     * @param string $period 'daily' or 'weekly'
     * @return array User activity data
     */
    public static function get_user_activity($period = 'daily') {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        if ($period === 'daily') {
            $start = date('Y-m-d 00:00:00', strtotime('-1 day'));
            $end = date('Y-m-d 23:59:59', strtotime('-1 day'));
        } else {
            $start = date('Y-m-d 00:00:00', strtotime('-7 days'));
            $end = date('Y-m-d 23:59:59', strtotime('-1 day'));
        }
        
        // Get user-related events
        $user_events = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND category IN ('user', 'authentication')
             ORDER BY created_at DESC 
             LIMIT 50",
            $start, $end
        ));
        
        // Get top active users
        $top_users = $wpdb->get_results($wpdb->prepare(
            "SELECT user_id, COUNT(*) as activity_count FROM $table 
             WHERE created_at BETWEEN %s AND %s AND user_id > 0
             GROUP BY user_id 
             ORDER BY activity_count DESC 
             LIMIT 10",
            $start, $end
        ));
        
        // Ensure arrays before counting
        $user_events = is_array($user_events) ? $user_events : array();
        $top_users = is_array($top_users) ? $top_users : array();
        
        return array(
            'period' => $period,
            'date_range' => array(
                'start' => $start,
                'end' => $end
            ),
            'user_events' => $user_events,
            'top_users' => $top_users,
            'total_user_events' => count($user_events)
        );
    }
    
    /**
     * Get weekly health statistics with real system health metrics
     * 
     * @return array Weekly health data
     */
    public static function get_weekly_health_statistics() {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // Use past 7 days including today
        $week_start = date('Y-m-d 00:00:00', strtotime('-7 days'));
        $week_end = date('Y-m-d 23:59:59');
        
        // Get basic statistics
        $total_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s",
            $week_start, $week_end
        ));
        
        $active_users = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT user_id) FROM $table 
             WHERE created_at BETWEEN %s AND %s AND user_id > 0",
            $week_start, $week_end
        ));
        
        // Get real system events by priority
        $critical_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND priority = 'critical'",
            $week_start, $week_end
        ));
        
        $high_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND priority = 'high'",
            $week_start, $week_end
        ));
        
        $medium_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND priority = 'medium'",
            $week_start, $week_end
        ));
        
        // Calculate real uptime using cron health and database connectivity
        $cron_uptime = self::check_cron_health($week_start, $week_end);
        $db_gaps = self::check_database_gaps($week_start, $week_end);
        
        // Start with cron-based uptime
        $uptime_percentage = $cron_uptime;
        
        // Reduce for database connectivity gaps
        if ($db_gaps > 0) {
            $uptime_percentage = max(70.0, $uptime_percentage - ($db_gaps * 5));
        }
        
        // Reduce for critical errors
        if ($critical_events > 0) {
            $uptime_percentage = max(60.0, $uptime_percentage - ($critical_events * 2));
        }
        
        // Get real plugin status
        $active_plugins = get_option('active_plugins', array());
        $plugin_count = count($active_plugins);
        
        // Get real theme status
        $current_theme = wp_get_theme();
        $theme_name = $current_theme->get('Name');
        
        // Get database health (check for recent database errors)
        $db_errors = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (event_key LIKE %s OR event_key LIKE %s)",
            $week_start, $week_end, '%database%', '%mysql%'
        ));
        
        // Real health metrics based on actual data
        $health_metrics = array(
            'Critical Events' => $critical_events,
            'High Priority Events' => $high_events,
            'Medium Priority Events' => $medium_events,
            'Active Plugins' => $plugin_count,
            'Current Theme' => $theme_name,
            'Database Errors' => $db_errors
        );
        
        return array(
            'period' => 'weekly',
            'date_range' => array(
                'start' => $week_start,
                'end' => $week_end
            ),
            'total_events' => intval($total_events),
            'active_users' => intval($active_users),
            'uptime_percentage' => round($uptime_percentage, 1),
            'health_metrics' => $health_metrics
        );
    }
    
    /**
     * Check WordPress cron health for uptime calculation
     * 
     * @param string $start_date Start date for period
     * @param string $end_date End date for period
     * @return float Uptime percentage based on cron health
     */
    private static function check_cron_health($start_date, $end_date) {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // Check for cron-related events (WordPress logs these automatically)
        $cron_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (event_key LIKE %s OR event_key LIKE %s OR event_key LIKE %s)",
            $start_date, $end_date, '%cron%', '%wp_cron%', '%scheduled%'
        ));
        
        // Check for daily activity patterns (cron should trigger regular activity)
        $daily_activity = $wpdb->get_results($wpdb->prepare(
            "SELECT DATE(created_at) as date, COUNT(*) as count 
             FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             GROUP BY DATE(created_at) 
             ORDER BY date",
            $start_date, $end_date
        ));
        
        $days_with_activity = count($daily_activity);
        $total_days = 7;
        
        // Base uptime on daily activity (cron should ensure some activity daily)
        $base_uptime = ($days_with_activity / $total_days) * 100;
        
        // If we have cron events, boost uptime (indicates system is running)
        if ($cron_events > 0) {
            $base_uptime = min(99.5, $base_uptime + 5);
        }
        
        // If no activity for multiple days, reduce uptime significantly
        // But be more lenient in development environments
        if ($days_with_activity < 3) {
            // In development, assume higher uptime even with low activity
            if (defined('WP_DEBUG') && WP_DEBUG) {
                $base_uptime = max(85.0, $base_uptime - 10);
            } else {
                $base_uptime = max(50.0, $base_uptime - 30);
            }
        }
        
        return $base_uptime;
    }
    
    /**
     * Check for database connectivity gaps
     * 
     * @param string $start_date Start date for period
     * @param string $end_date End date for period
     * @return int Number of potential database gaps
     */
    private static function check_database_gaps($start_date, $end_date) {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // Look for gaps longer than 6 hours without any activity
        // This might indicate database connectivity issues
        // Using a simpler approach that works with older MySQL versions
        $gaps = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM (
                SELECT t1.created_at, t2.created_at as prev_time
                FROM $table t1
                LEFT JOIN $table t2 ON t2.created_at = (
                    SELECT MAX(created_at) 
                    FROM $table t3 
                    WHERE t3.created_at < t1.created_at 
                    AND t3.created_at BETWEEN %s AND %s
                )
                WHERE t1.created_at BETWEEN %s AND %s
            ) as time_gaps 
            WHERE prev_time IS NOT NULL 
            AND TIMESTAMPDIFF(HOUR, prev_time, created_at) > 6",
            $start_date, $end_date, $start_date, $end_date
        ));
        
        return intval($gaps);
    }
    
    /**
     * Get weekly performance statistics with real performance metrics
     * 
     * @return array Weekly performance data
     */
    public static function get_weekly_performance_statistics() {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // Use past 7 days including today
        $week_start = date('Y-m-d 00:00:00', strtotime('-7 days'));
        $week_end = date('Y-m-d 23:59:59');
        
        // Get basic statistics (event counts still from log table)
        $total_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s",
            $week_start, $week_end
        ));
        
        // --- NEW: Get performance samples from transient ---
        $samples = get_transient('sentinel_performance_samples');
        if (!is_array($samples)) {
            $samples = array();
        }
        $sample_count = count($samples);
        $peak_memory_bytes = 0;
        $total_db_queries = 0;
        $total_response_time = 0;
        $max_memory = 0;
        $max_db_queries = 0;
        $max_response_time = 0;
        foreach ($samples as $sample) {
            $mem = isset($sample['memory_bytes']) ? (int)$sample['memory_bytes'] : 0;
            $dbq = isset($sample['db_queries']) ? (int)$sample['db_queries'] : 0;
            $rt = isset($sample['response_time_ms']) ? (float)$sample['response_time_ms'] : 0;
            $total_db_queries += $dbq;
            $total_response_time += $rt;
            if ($mem > $max_memory) $max_memory = $mem;
            if ($dbq > $max_db_queries) $max_db_queries = $dbq;
            if ($rt > $max_response_time) $max_response_time = $rt;
        }
        $avg_db_queries = $sample_count ? round($total_db_queries / $sample_count, 1) : 'N/A';
        $avg_response_time = $sample_count ? round($total_response_time / $sample_count, 1) : 'N/A';
        $peak_memory_formatted = $max_memory ? size_format($max_memory) : 'N/A';
        // Note: Transient will auto-expire after 8 days, no need to clear manually
        
        // Get real performance events (high priority events that might indicate performance issues)
        $performance_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (priority IN ('high', 'critical') OR event_key LIKE %s OR event_key LIKE %s)",
            $week_start, $week_end, '%slow%', '%timeout%'
        ));
        $timeout_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND event_key LIKE %s",
            $week_start, $week_end, '%timeout%'
        ));
        // --- END NEW ---
        $performance_trends = array(
            array('metric' => 'Total Events', 'value' => number_format($total_events)),
            array('metric' => 'Peak Memory (Week)', 'value' => $peak_memory_formatted),
            array('metric' => 'Avg DB Queries/Request', 'value' => $avg_db_queries),
            array('metric' => 'Avg Response Time', 'value' => $avg_response_time . 'ms'),
            array('metric' => 'Performance Events', 'value' => $performance_events),
            array('metric' => 'Timeout Events', 'value' => $timeout_events),
            array('metric' => 'Performance Samples', 'value' => $sample_count)
        );
        return array(
            'period' => 'weekly',
            'date_range' => array(
                'start' => $week_start,
                'end' => $week_end
            ),
            'total_events' => intval($total_events),
            'avg_response_time' => $avg_response_time,
            'peak_memory' => $peak_memory_formatted,
            'performance_trends' => $performance_trends
        );
    }
    
    /**
     * Get weekly security statistics with security metrics
     * 
     * @return array Weekly security data
     */
    public static function get_weekly_security_statistics() {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // Use past 7 days including today
        $week_start = date('Y-m-d 00:00:00', strtotime('-7 days'));
        $week_end = date('Y-m-d 23:59:59');
        
        // Get security events
        $security_events = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (category = 'security' OR priority IN ('critical', 'high') OR event_key LIKE %s)",
            $week_start, $week_end, '%security%'
        ));
        
        // Get failed login attempts
        $failed_logins = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (event_key LIKE %s OR event_key LIKE %s)",
            $week_start, $week_end, '%login_failed%', '%authentication_failed%'
        ));
        
        // Get security incidents
        $security_incidents = $wpdb->get_results($wpdb->prepare(
            "SELECT event_key, created_at FROM $table 
             WHERE created_at BETWEEN %s AND %s 
             AND (category = 'security' OR priority IN ('critical', 'high'))
             ORDER BY created_at DESC 
             LIMIT 10",
            $week_start, $week_end
        ));
        
        // Format incidents for display
        $formatted_incidents = array();
        foreach ($security_incidents as $incident) {
            $formatted_incidents[] = array(
                'type' => ucwords(str_replace('_', ' ', $incident->event_key)),
                'date' => date('M j, Y', strtotime($incident->created_at))
            );
        }
        
        return array(
            'period' => 'weekly',
            'date_range' => array(
                'start' => $week_start,
                'end' => $week_end
            ),
            'security_events' => intval($security_events),
            'failed_logins' => intval($failed_logins),
            'security_incidents' => $formatted_incidents
        );
    }
    
    /**
     * Process daily digest reports
     */
    public static function process_daily_digests() {
        // Prevent duplicate sends from cron race conditions.
        $last_sent = (int) get_option('sentinel_daily_digest_last_sent', 0);
        if ($last_sent > 0 && (time() - $last_sent) < 20 * HOUR_IN_SECONDS) {
            error_log('[Sentinel] Daily digest skipped — already sent ' . (time() - $last_sent) . 's ago');
            return;
        }
        update_option('sentinel_daily_digest_last_sent', time(), false);

        error_log('[Sentinel] Daily digest processing started');
        
        $daily_digests = array('daily_summary', 'daily_error', 'daily_user');
        $enabled_digests = array();
        
        foreach ($daily_digests as $digest_type) {
            if (self::is_digest_enabled($digest_type)) {
                $enabled_digests[] = $digest_type;
            }
        }
        
        if (empty($enabled_digests)) {
            error_log('[Sentinel] No daily digests enabled, skipping processing');
            return;
        }
        
        error_log('[Sentinel] Processing enabled daily digests: ' . implode(', ', $enabled_digests));
        
        // Collect all data for enabled digests
        $combined_data = array();
        $settings = get_option('sentinel_log_management', array());
        $section_toggles = [
            'daily_summary' => !empty($settings['sentinel_email_daily_summary']),
            'daily_error'   => !empty($settings['sentinel_email_daily_error']),
            'daily_user'    => !empty($settings['sentinel_email_daily_user'])
        ];
        
        foreach ($enabled_digests as $digest_type) {
            switch ($digest_type) {
                case 'daily_summary':
                    $stats = self::get_daily_statistics();
                    error_log('[Sentinel] Daily Summary - Total events: ' . $stats['total_events'] . ', Active users: ' . $stats['active_users']);
                    $combined_data['daily_summary'] = $stats;
                    break;
                    
                case 'daily_error':
                    $error_data = self::get_error_events('daily');
                    error_log('[Sentinel] Daily Error Report - Total errors: ' . $error_data['total_errors']);
                    $combined_data['daily_error'] = $error_data;
                    break;
                    
                case 'daily_user':
                    $user_data = self::get_user_activity('daily');
                    error_log('[Sentinel] Daily User Activity - Total user events: ' . $user_data['total_user_events']);
                    $combined_data['daily_user'] = $user_data;
                    break;
            }
        }
        
        // Send one combined email with all enabled sections
        if (!empty($combined_data)) {
            self::send_combined_daily_digest_email($combined_data, $section_toggles);
        }
        
        error_log('[Sentinel] Daily digest processing completed');
    }
    
    /**
     * Process weekly digest reports
     */
    public static function process_weekly_digests() {
        $last_sent = (int) get_option('sentinel_weekly_digest_last_sent', 0);
        if ($last_sent > 0 && (time() - $last_sent) < 5 * DAY_IN_SECONDS) {
            error_log('[Sentinel] Weekly digest skipped — already sent ' . (time() - $last_sent) . 's ago');
            return;
        }
        update_option('sentinel_weekly_digest_last_sent', time(), false);

        error_log('[Sentinel] Weekly digest processing started');
        
        $weekly_digests = array('weekly_health', 'weekly_performance', 'weekly_security');
        $enabled_digests = array();
        
        foreach ($weekly_digests as $digest_type) {
            if (self::is_digest_enabled($digest_type)) {
                $enabled_digests[] = $digest_type;
            }
        }
        
        if (empty($enabled_digests)) {
            error_log('[Sentinel] No weekly digests enabled, skipping processing');
            return;
        }
        
        error_log('[Sentinel] Processing enabled weekly digests: ' . implode(', ', $enabled_digests));
        
        // Collect all data for enabled digests
        $combined_data = array();
        $settings = get_option('sentinel_log_management', array());
        $section_toggles = [
            'weekly_health' => !empty($settings['sentinel_email_weekly_health']),
            'weekly_performance' => !empty($settings['sentinel_email_weekly_performance']),
            'weekly_security' => !empty($settings['sentinel_email_weekly_security'])
        ];
        
        foreach ($enabled_digests as $digest_type) {
            switch ($digest_type) {
                case 'weekly_health':
                    $stats = self::get_weekly_health_statistics();
                    error_log('[Sentinel] Weekly Health Report - Total events: ' . $stats['total_events'] . ', Uptime: ' . $stats['uptime_percentage'] . '%');
                    $combined_data['weekly_health'] = $stats;
                    break;
                    
                case 'weekly_performance':
                    $stats = self::get_weekly_performance_statistics();
                    error_log('[Sentinel] Weekly Performance Report - Avg response: ' . $stats['avg_response_time'] . 'ms, Peak memory: ' . $stats['peak_memory']);
                    $combined_data['weekly_performance'] = $stats;
                    break;
                    
                case 'weekly_security':
                    $stats = self::get_weekly_security_statistics();
                    error_log('[Sentinel] Weekly Security Report - Security events: ' . $stats['security_events'] . ', Failed logins: ' . $stats['failed_logins']);
                    $combined_data['weekly_security'] = $stats;
                    break;
            }
        }
        
        // Send one combined email with all enabled sections
        if (!empty($combined_data)) {
            self::send_combined_weekly_digest_email($combined_data, $section_toggles);
        }
        
        error_log('[Sentinel] Weekly digest processing completed');
    }
    
    /**
     * Send combined daily digest email with all enabled sections
     * 
     * @param array $combined_data All digest data
     * @param array $section_toggles Which sections are enabled
     */
    private static function send_combined_daily_digest_email($combined_data, $section_toggles) {
        // Check if email templates class exists
        if (!class_exists('Sentinel_Email_Templates')) {
            error_log('[Sentinel] Email templates class not found, skipping combined daily digest email');
            return;
        }
        
        // Get notification email from settings
        $settings = get_option('sentinel_log_management', array());
        $to_email = !empty($settings['notification_email']) ? $settings['notification_email'] : get_option('admin_email');
        
        // Generate combined email content
        $email_data = Sentinel_Email_Templates::generate_combined_daily_digest_email($combined_data, $section_toggles);
        
        if (!$email_data) {
            error_log('[Sentinel] Failed to generate combined daily digest email data');
            return;
        }
        
        // Send email using WordPress mail function
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
            'From: Sentinel <' . get_option('admin_email') . '>'
        );
        
        $sent = wp_mail($to_email, $email_data['subject'], $email_data['html_body'], $headers);
        
        if ($sent) {
            error_log('[Sentinel] Combined daily digest email sent successfully to ' . $to_email);
        } else {
            error_log('[Sentinel] Failed to send combined daily digest email to ' . $to_email);
        }
        
        // Log email content for debugging (only in debug mode)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[Sentinel Email Debug] Combined Daily Digest');
            error_log('[Sentinel Email Debug] To: ' . $to_email);
            error_log('[Sentinel Email Debug] Subject: ' . $email_data['subject']);
            error_log('[Sentinel Email Debug] Plain Text: ' . $email_data['plain_body']);
            error_log('[Sentinel Email Debug] HTML Version: ' . $email_data['html_body']);
        }
    }
    
    /**
     * Send combined weekly digest email with all enabled sections
     * 
     * @param array $combined_data All digest data
     * @param array $section_toggles Which sections are enabled
     */
    private static function send_combined_weekly_digest_email($combined_data, $section_toggles) {
        // Check if email templates class exists
        if (!class_exists('Sentinel_Email_Templates')) {
            error_log('[Sentinel] Email templates class not found, skipping combined weekly digest email');
            return;
        }
        
        // Get notification email from settings
        $settings = get_option('sentinel_log_management', array());
        $to_email = !empty($settings['notification_email']) ? $settings['notification_email'] : get_option('admin_email');
        
        // Generate combined email content
        $email_data = Sentinel_Email_Templates::generate_combined_weekly_digest_email($combined_data, $section_toggles);
        
        if (!$email_data) {
            error_log('[Sentinel] Failed to generate combined weekly digest email data');
            return;
        }
        
        // Send email using WordPress mail function
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
            'From: Sentinel <' . get_option('admin_email') . '>'
        );
        
        $sent = wp_mail($to_email, $email_data['subject'], $email_data['html_body'], $headers);
        
        if ($sent) {
            error_log('[Sentinel] Combined weekly digest email sent successfully to ' . $to_email);
        } else {
            error_log('[Sentinel] Failed to send combined weekly digest email to ' . $to_email);
        }
        
        // Log email content for debugging (only in debug mode)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[Sentinel Email Debug] Combined Weekly Digest');
            error_log('[Sentinel Email Debug] To: ' . $to_email);
            error_log('[Sentinel Email Debug] Subject: ' . $email_data['subject']);
            error_log('[Sentinel Email Debug] Plain Text: ' . $email_data['plain_body']);
            error_log('[Sentinel Email Debug] HTML Version: ' . $email_data['html_body']);
        }
    }
} 