<?php
/**
 * Name: Email Reports
 * Description: Send scheduled email reports with analytics, security, and site health data to specified recipients
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Stay Informed",
 *     "description": "Receive regular email digests with key metrics about your site's performance and security."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate reporting instead of manually checking dashboards every day."
 *   }
 * ]
 * Added: 2026-02-06
 * Tags: email, reports, analytics, notifications, scheduling, digest
 * WhereToFind: {
 *   "location": "Email Reports",
 *   "url": "admin.php?page=switchboard-email-reports",
 *   "instructions": "Configure recipients, schedule, and report sections. Use Preview to see the report before enabling.",
 *   "newTab": false
 * }
 */

if (!defined('ABSPATH')) {
    exit;
}

class SwitchboardEmailReports {

    /**
     * Option name for settings
     */
    private $option_name = 'switchboard_email-reports_settings';

    /**
     * Database table name (without prefix)
     */
    private $table_name;

    /**
     * Settings cache
     */
    private $settings = null;

    /**
     * Constructor
     */
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'switchboard_report_log';

        // Create table if needed
        add_action('admin_init', [$this, 'maybe_create_table']);

        // Register admin page
        add_action('admin_menu', [$this, 'register_admin_page']);

        // Enqueue admin assets
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);

        // AJAX handlers
        add_action('wp_ajax_switchboard_email_reports_preview', [$this, 'ajax_preview_report']);
        add_action('wp_ajax_switchboard_email_reports_preview_section', [$this, 'ajax_preview_section']);
        add_action('wp_ajax_switchboard_email_reports_test', [$this, 'ajax_send_test']);
        add_action('wp_ajax_switchboard_email_reports_send_now', [$this, 'ajax_send_now']);
        add_action('wp_ajax_switchboard_email_reports_history', [$this, 'ajax_get_history']);
        add_action('wp_ajax_switchboard_email_reports_delete', [$this, 'ajax_delete_history']);
        add_action('wp_ajax_switchboard_email_reports_clear_all', [$this, 'ajax_clear_all_history']);

        // Cron handlers
        add_action('switchboard_send_weekly_report', [$this, 'send_weekly_report']);
        add_action('switchboard_send_monthly_report', [$this, 'send_monthly_report']);

        // Register custom cron schedules
        add_filter('cron_schedules', [$this, 'add_cron_schedules']);
    }

    /**
     * Register data locations for cleanup
     */
    public function register_data_locations() {
        return [
            'options' => [
                $this->option_name,
            ],
            'tables' => [
                'switchboard_report_log',
            ],
        ];
    }

    /**
     * Called when module is activated
     */
    public function activate() {
        $this->maybe_create_table();
        $this->schedule_reports();
    }

    /**
     * Called when module is deactivated
     */
    public function deactivate() {
        wp_clear_scheduled_hook('switchboard_send_weekly_report');
        wp_clear_scheduled_hook('switchboard_send_monthly_report');
    }

    /**
     * Add custom cron schedules
     */
    public function add_cron_schedules($schedules) {
        $schedules['weekly'] = [
            'interval' => WEEK_IN_SECONDS,
            'display'  => __('Once Weekly', 'wpswitchboard'),
        ];
        $schedules['monthly'] = [
            'interval' => MONTH_IN_SECONDS,
            'display'  => __('Once Monthly', 'wpswitchboard'),
        ];
        return $schedules;
    }

    /**
     * Schedule report cron jobs based on settings
     */
    private function schedule_reports() {
        $settings = $this->get_settings();

        // Clear existing schedules
        wp_clear_scheduled_hook('switchboard_send_weekly_report');
        wp_clear_scheduled_hook('switchboard_send_monthly_report');

        if (empty($settings['enabled'])) {
            return;
        }

        $schedule = $settings['schedule'] ?? 'weekly';
        $time = $settings['time'] ?? '09:00';
        $day_of_week = intval($settings['day_of_week'] ?? 1);
        $day_of_month = intval($settings['day_of_month'] ?? 1);

        // Calculate next run time
        $next_run = $this->calculate_next_run_time($schedule, $time, $day_of_week, $day_of_month);

        $hook = ($schedule === 'weekly') ? 'switchboard_send_weekly_report' : 'switchboard_send_monthly_report';
        $recurrence = ($schedule === 'weekly') ? 'weekly' : 'monthly';

        wp_schedule_event($next_run, $recurrence, $hook, [], true);
    }

    /**
     * Calculate next run timestamp
     */
    private function calculate_next_run_time($schedule, $time, $day_of_week, $day_of_month) {
        $time_parts = explode(':', $time);
        $hour = intval($time_parts[0] ?? 9);
        $minute = intval($time_parts[1] ?? 0);

        // Use WordPress timezone for calculations, then convert to UTC for wp_schedule_event()
        $wp_tz = wp_timezone();
        $now = new DateTimeImmutable('now', $wp_tz);

        if ($schedule === 'weekly') {
            $current_dow = intval($now->format('w'));
            $target_dow = $day_of_week;

            $days_until = ($target_dow - $current_dow + 7) % 7;
            $target = $now->modify("+{$days_until} days")->setTime($hour, $minute, 0);

            if ($days_until === 0 && $now >= $target) {
                $target = $target->modify('+7 days');
            }

            return $target->getTimestamp();

        } elseif ($schedule === 'monthly') {
            $current_dom = intval($now->format('j'));
            $current_month = intval($now->format('n'));
            $current_year = intval($now->format('Y'));

            if ($current_dom < $day_of_month) {
                $max_day = cal_days_in_month(CAL_GREGORIAN, $current_month, $current_year);
                $target_day = min($day_of_month, $max_day);
                $target = $now->setDate($current_year, $current_month, $target_day)->setTime($hour, $minute, 0);
            } else {
                $next_month = $current_month + 1;
                $next_year = $current_year;
                if ($next_month > 12) {
                    $next_month = 1;
                    $next_year++;
                }
                $max_day = cal_days_in_month(CAL_GREGORIAN, $next_month, $next_year);
                $target_day = min($day_of_month, $max_day);
                $target = $now->setDate($next_year, $next_month, $target_day)->setTime($hour, $minute, 0);
            }

            return $target->getTimestamp();
        }

        return time() + DAY_IN_SECONDS;
    }

    /**
     * Create database table if it doesn't exist
     */
    public function maybe_create_table() {
        // Skip if table already created (avoid SHOW TABLES query on every admin page load)
        $db_version = get_option('switchboard_email_reports_db_version', '0');
        if ($db_version === '1.0') {
            return;
        }

        global $wpdb;

        $table_name = $this->table_name;
        $charset_collate = $wpdb->get_charset_collate();

        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
            $sql = "CREATE TABLE $table_name (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                report_type VARCHAR(20) NOT NULL DEFAULT 'scheduled',
                schedule_type VARCHAR(20) DEFAULT NULL,
                recipients TEXT NOT NULL,
                sections TEXT NOT NULL,
                date_range_from DATE NOT NULL,
                date_range_to DATE NOT NULL,
                status VARCHAR(20) NOT NULL DEFAULT 'pending',
                error_message TEXT DEFAULT NULL,
                sent_at DATETIME DEFAULT NULL,
                created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY status (status),
                KEY sent_at (sent_at),
                KEY report_type (report_type)
            ) $charset_collate;";

            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta($sql);
        }

        update_option('switchboard_email_reports_db_version', '1.0', true);
    }

    /**
     * Get settings with defaults
     */
    public function get_settings() {
        if ($this->settings !== null) {
            return $this->settings;
        }

        $defaults = [
            'enabled'                 => false,
            'schedule'                => 'weekly',
            'day_of_week'             => 1,
            'day_of_month'            => 1,
            'time'                    => '09:00',
            'logo_id'                 => 0,
            'company_name'            => '',
            'primary_color'           => '#2271b1',
            'footer_text'             => '',
            'report_period'           => 'last_7_days',
            // Delivery mode: 'combined' (one email with all sections) or 'separate' (per-section emails)
            'delivery_mode'           => 'combined',
            // Global recipients for combined mode
            'global_recipients_type'  => 'admin',
            'global_custom_recipients' => '',
            // Per-section settings: section_id => ['enabled' => bool, 'recipients_type' => 'admin'|'custom', 'custom_recipients' => '']
            'section_settings'        => [],
        ];

        $settings = get_option($this->option_name, []);
        $this->settings = wp_parse_args($settings, $defaults);

        return $this->settings;
    }

    /**
     * Save settings
     */
    public function save_settings($module, $settings) {
        if ($module !== 'email-reports') {
            return;
        }

        // Parse per-section settings
        $section_settings = [];
        if (!empty($settings['section_settings']) && is_array($settings['section_settings'])) {
            foreach ($settings['section_settings'] as $section_id => $section_config) {
                $section_id = sanitize_key($section_id);

                // Parse custom recipients
                $custom_recipients = '';
                if (!empty($section_config['custom_recipients'])) {
                    $lines = preg_split('/\r\n|\r|\n/', $section_config['custom_recipients']);
                    $emails = array_filter(array_map('trim', $lines), 'is_email');
                    $custom_recipients = implode("\n", $emails);
                }

                $section_settings[$section_id] = [
                    'enabled'           => !empty($section_config['enabled']),
                    'recipients_type'   => in_array($section_config['recipients_type'] ?? '', ['admin', 'custom'], true)
                        ? $section_config['recipients_type']
                        : 'admin',
                    'custom_recipients' => $custom_recipients,
                ];
            }
        }

        // Parse global custom recipients
        $global_custom_recipients = '';
        if (!empty($settings['global_custom_recipients'])) {
            $lines = preg_split('/\r\n|\r|\n/', $settings['global_custom_recipients']);
            $emails = array_filter(array_map('trim', $lines), 'is_email');
            $global_custom_recipients = implode("\n", $emails);
        }

        $sanitized = [
            'enabled'                  => !empty($settings['enabled']),
            'schedule'                 => in_array($settings['schedule'] ?? '', ['weekly', 'monthly'], true) ? $settings['schedule'] : 'weekly',
            'day_of_week'              => max(0, min(6, intval($settings['day_of_week'] ?? 1))),
            'day_of_month'             => max(1, min(28, intval($settings['day_of_month'] ?? 1))),
            'time'                     => sanitize_text_field($settings['time'] ?? '09:00'),
            'logo_id'                  => intval($settings['logo_id'] ?? 0),
            'company_name'             => sanitize_text_field($settings['company_name'] ?? ''),
            'primary_color'            => sanitize_hex_color($settings['primary_color'] ?? '#2271b1') ?: '#2271b1',
            'footer_text'              => sanitize_textarea_field($settings['footer_text'] ?? ''),
            'report_period'            => in_array($settings['report_period'] ?? '', ['last_7_days', 'last_30_days', 'last_month'], true) ? $settings['report_period'] : 'last_7_days',
            'delivery_mode'            => in_array($settings['delivery_mode'] ?? '', ['combined', 'separate'], true) ? $settings['delivery_mode'] : 'combined',
            'global_recipients_type'   => in_array($settings['global_recipients_type'] ?? '', ['admin', 'custom'], true) ? $settings['global_recipients_type'] : 'admin',
            'global_custom_recipients' => $global_custom_recipients,
            'section_settings'         => $section_settings,
        ];

        update_option($this->option_name, $sanitized);
        $this->settings = null; // Clear cache

        // Reschedule reports
        $this->schedule_reports();
    }

    /**
     * Save settings from POST data
     */
    private function save_settings_from_post() {
        // Parse section settings from POST
        $section_settings = [];
        if (isset($_POST['section_settings']) && is_array($_POST['section_settings'])) {
            foreach ($_POST['section_settings'] as $section_id => $config) {
                $section_settings[sanitize_key($section_id)] = [
                    'enabled'           => !empty($config['enabled']),
                    'recipients_type'   => sanitize_text_field($config['recipients_type'] ?? 'admin'),
                    'custom_recipients' => sanitize_textarea_field($config['custom_recipients'] ?? ''),
                ];
            }
        }


        $settings = [
            'enabled'                  => isset($_POST['setting_enabled']),
            'schedule'                 => sanitize_text_field($_POST['setting_schedule'] ?? 'weekly'),
            'day_of_week'              => intval($_POST['setting_day_of_week'] ?? 1),
            'day_of_month'             => intval($_POST['setting_day_of_month'] ?? 1),
            'time'                     => sanitize_text_field($_POST['setting_time'] ?? '09:00'),
            'logo_id'                  => intval($_POST['setting_logo_id'] ?? 0),
            'company_name'             => sanitize_text_field($_POST['setting_company_name'] ?? ''),
            'primary_color'            => sanitize_hex_color($_POST['setting_primary_color'] ?? '#2271b1') ?: '#2271b1',
            'footer_text'              => sanitize_textarea_field($_POST['setting_footer_text'] ?? ''),
            'report_period'            => sanitize_text_field($_POST['setting_report_period'] ?? 'last_7_days'),
            'delivery_mode'            => sanitize_text_field($_POST['setting_delivery_mode'] ?? 'combined'),
            'global_recipients_type'   => sanitize_text_field($_POST['setting_global_recipients_type'] ?? 'admin'),
            'global_custom_recipients' => sanitize_textarea_field($_POST['setting_global_custom_recipients'] ?? ''),
            'section_settings'         => $section_settings,
        ];

        $this->save_settings('email-reports', $settings);
    }

    /**
     * Register admin page
     */
    public function register_admin_page() {
        add_submenu_page(
            'switchboard',
            __('Email Reports', 'wpswitchboard'),
            __('Email Reports', 'wpswitchboard'),
            'manage_options',
            'switchboard-email-reports',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        // Check if we're on the email-reports page (check both hook and GET parameter)
        $is_email_reports_page = (
            (isset($_GET['page']) && $_GET['page'] === 'switchboard-email-reports') ||
            strpos($hook, 'email-reports') !== false
        );

        if (!$is_email_reports_page) {
            return;
        }

        // Enqueue media uploader
        wp_enqueue_media();

        // Enqueue color picker
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        // Load main Switchboard admin styles (contains base color variables)
        wp_enqueue_style(
            'switchboard-admin',
            SWITCHBOARD_URL . 'switchboard-admin.css',
            [],
            SWITCHBOARD_VERSION
        );

        // Main admin styles
        wp_enqueue_style(
            'switchboard-email-reports-admin',
            SWITCHBOARD_URL . 'assets/email-reports/admin.css',
            ['switchboard-admin'],
            SWITCHBOARD_VERSION
        );

        // Main admin script
        wp_enqueue_script(
            'switchboard-email-reports-admin',
            SWITCHBOARD_URL . 'assets/email-reports/admin.js',
            ['jquery', 'wp-color-picker'],
            SWITCHBOARD_VERSION,
            true
        );

        wp_localize_script('switchboard-email-reports-admin', 'switchboardEmailReports', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('switchboard_email_reports'),
            'i18n'    => [
                'sending'         => __('Sending...', 'wpswitchboard'),
                'saving'          => __('Saving...', 'wpswitchboard'),
                'sendTest'        => __('Send Test Email', 'wpswitchboard'),
                'sendNow'         => __('Send Now', 'wpswitchboard'),
                'preview'         => __('Preview Report', 'wpswitchboard'),
                'loading'         => __('Loading...', 'wpswitchboard'),
                'success'         => __('Test email sent successfully!', 'wpswitchboard'),
                'error'           => __('Failed to send email:', 'wpswitchboard'),
                'confirmDelete'   => __('Are you sure you want to delete this report log?', 'wpswitchboard'),
                'confirmSend'     => __('Send report to all configured recipients now?', 'wpswitchboard'),
                'confirmClearAll' => __('Are you sure you want to clear all report history? This cannot be undone.', 'wpswitchboard'),
                'selectImage'     => __('Select Logo', 'wpswitchboard'),
                'useImage'        => __('Use this image', 'wpswitchboard'),
                'connectionErr'   => __('Connection error. Please try again.', 'wpswitchboard'),
                'settingsSaved'   => __('Settings saved successfully!', 'wpswitchboard'),
                'saveFailed'      => __('Failed to save settings. Please try again.', 'wpswitchboard'),
                'unsavedChanges'  => __('Unsaved', 'wpswitchboard'),
            ],
        ]);
    }

    /**
     * Render admin page
     */
    public function render_admin_page() {
        $settings_saved = false;
        $settings_error = '';

        // Handle form submission
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sb_er_nonce'])) {
            if (!wp_verify_nonce($_POST['sb_er_nonce'], 'switchboard_email_reports_save')) {
                $settings_error = __('Security check failed. Please try again.', 'wpswitchboard');
            } elseif (!current_user_can('manage_options')) {
                $settings_error = __('You do not have permission to save settings.', 'wpswitchboard');
            } else {
                $this->save_settings_from_post();
                $settings_saved = true;
            }
        }

        $settings = $this->get_settings();
        $tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'settings';

        // Get registered sections
        $registry = class_exists('Switchboard_Report_Registry') ? Switchboard_Report_Registry::get_instance() : null;
        $sections = $registry ? $registry->get_sections(true) : [];

        ?>
        <div class="wrap sb-module-wrap sb-er-wrap">
            <!-- Header -->
            <div class="sb-module-header">
                <div class="sb-module-header-left">
                    <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                    </svg>
                    <div>
                        <h1 class="sb-module-title">
                            <?php esc_html_e('Email Reports', 'wpswitchboard'); ?>
                            <span class="switchboard-badge">SWITCHBOARD</span>
                        </h1>
                        <p class="sb-module-subtitle"><?php esc_html_e('Schedule automated reports with analytics, security, and site health data', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-header-right">
                    <?php if ($settings['enabled']) : ?>
                        <span class="sb-module-badge sb-module-badge-success"><span class="sb-status-dot sb-status-dot-green"></span><?php echo esc_html($this->get_next_scheduled_label()); ?></span>
                    <?php else : ?>
                        <span class="sb-module-badge sb-module-badge-secondary"><span class="sb-status-dot sb-status-dot-red"></span><?php esc_html_e('Reports disabled', 'wpswitchboard'); ?></span>
                    <?php endif; ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-email-reports&tab=settings')); ?>" class="sb-er-tab <?php echo $tab === 'settings' ? 'active' : ''; ?>">
                        <?php esc_html_e('Config', 'wpswitchboard'); ?>
                    </a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-email-reports&tab=history')); ?>" class="sb-er-tab <?php echo $tab === 'history' ? 'active' : ''; ?>">
                        <?php esc_html_e('History', 'wpswitchboard'); ?>
                    </a>
                </div>
            </div>

            <?php if ($settings_saved) : ?>
                <div class="notice notice-success" style="margin: 0 0 20px 0;"><p><?php esc_html_e('Settings saved successfully!', 'wpswitchboard'); ?></p></div>
            <?php elseif ($settings_error) : ?>
                <div class="notice notice-error" style="margin: 0 0 20px 0;"><p><?php echo esc_html($settings_error); ?></p></div>
            <?php endif; ?>

            <!-- Content -->
            <?php
            switch ($tab) {
                case 'history':
                    $this->render_history_tab();
                    break;
                default:
                    $this->render_settings_tab($settings, $sections);
                    break;
            }
            ?>
        </div>
        <?php
    }

    /**
     * Render settings tab
     */
    private function render_settings_tab($settings, $sections) {
        $days_of_week = [
            0 => __('Sunday', 'wpswitchboard'),
            1 => __('Monday', 'wpswitchboard'),
            2 => __('Tuesday', 'wpswitchboard'),
            3 => __('Wednesday', 'wpswitchboard'),
            4 => __('Thursday', 'wpswitchboard'),
            5 => __('Friday', 'wpswitchboard'),
            6 => __('Saturday', 'wpswitchboard'),
        ];

        $logo_url = '';
        if (!empty($settings['logo_id'])) {
            $logo_url = wp_get_attachment_image_url($settings['logo_id'], 'medium');
        }

        $admin_email = get_option('admin_email');
        $section_settings = $settings['section_settings'] ?? [];

        // Get the first available section for initial selection
        $first_section_id = '';
        foreach ($sections as $section_id => $section) {
            if (!empty($section['available'])) {
                $first_section_id = $section_id;
                break;
            }
        }

        ?>
        <form method="post" action="" class="sb-er-form" id="sb-er-settings-form">
            <?php wp_nonce_field('switchboard_email_reports_save', 'sb_er_nonce'); ?>

            <div class="sb-er-layout">
                <!-- LEFT SIDEBAR - Settings & Sections Navigation -->
                <div class="sb-er-sidebar">
                    <div class="sb-module-card">
                        <div class="sb-module-card-body" style="padding: 8px;">
                            <div class="sb-er-sections-list">
                                <!-- Settings Item (Branding & Schedule) -->
                                <button type="button" class="sb-er-section-item sb-er-settings-item active"
                                     data-section="settings"
                                     data-title="<?php esc_attr_e('Settings', 'wpswitchboard'); ?>"
                                     data-description="<?php esc_attr_e('Configure branding and schedule options', 'wpswitchboard'); ?>">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="18" height="18" style="flex-shrink: 0;">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    </svg>
                                    <span class="sb-er-section-item-name"><?php esc_html_e('Settings', 'wpswitchboard'); ?></span>
                                </button>

                                <!-- Divider -->
                                <div class="sb-er-sidebar-divider">
                                    <span><?php esc_html_e('Report Sections', 'wpswitchboard'); ?></span>
                                </div>

                                <!-- Section Items -->
                                <?php if (empty($sections)) : ?>
                                    <p class="sb-er-empty-msg"><?php esc_html_e('No sections available. Enable modules to see sections.', 'wpswitchboard'); ?></p>
                                <?php else : ?>
                                    <?php
                                    // Sort sections: active (available) first, inactive last
                                    uasort($sections, function($a, $b) {
                                        $a_available = !empty($a['available']) ? 1 : 0;
                                        $b_available = !empty($b['available']) ? 1 : 0;
                                        return $b_available - $a_available; // Descending (active first)
                                    });
                                    ?>
                                    <?php foreach ($sections as $section_id => $section) :
                                        $is_available = !empty($section['available']);
                                        ?>
                                        <button type="button" class="sb-er-section-item <?php echo !$is_available ? 'disabled' : ''; ?>"
                                             data-section="<?php echo esc_attr($section_id); ?>"
                                             data-title="<?php echo esc_attr($section['title']); ?>"
                                             data-description="<?php echo esc_attr($section['description'] ?? ''); ?>">
                                            <span class="sb-er-section-item-name"><?php echo esc_html($section['title']); ?></span>
                                            <?php if (!$is_available) : ?>
                                                <?php
                                                $module_name = ucwords(str_replace(['-', '_'], ' ', $section['module'] ?? ''));
                                                /* translators: %s: module name */
                                                $tooltip = sprintf(__('Enable "%s" module to include in reports', 'wpswitchboard'), $module_name);
                                                ?>
                                                <span class="sb-module-badge sb-module-badge-error sb-er-tooltip" data-tooltip="<?php echo esc_attr($tooltip); ?>"><?php esc_html_e('Inactive', 'wpswitchboard'); ?></span>
                                            <?php endif; ?>
                                        </button>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- MAIN CONTENT - All Configuration -->
                <div class="sb-er-main">
                    <!-- Settings Panel (Branding & Schedule) - shown by default -->
                    <div class="sb-er-panel" id="settings-panel">
                        <div class="sb-module-card">
                            <div class="sb-module-card-header">
                                <div class="sb-module-card-header-left">
                                    <h2 class="sb-module-card-title" id="panel-title"><?php esc_html_e('Settings', 'wpswitchboard'); ?></h2>
                                    <p class="sb-module-card-desc" id="panel-desc"><?php esc_html_e('Configure branding and schedule options', 'wpswitchboard'); ?></p>
                                </div>
                            </div>
                            <div class="sb-module-card-body">
                                <div class="sb-er-settings-grid">
                                    <!-- Branding -->
                                    <div class="sb-er-settings-section">
                                        <h3 class="sb-er-settings-section-title"><?php esc_html_e('Branding', 'wpswitchboard'); ?></h3>
                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Logo', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <div class="sb-er-logo-upload">
                                                    <input type="hidden" name="setting_logo_id" id="setting_logo_id" value="<?php echo esc_attr($settings['logo_id']); ?>">
                                                    <div class="sb-er-logo-preview" id="logo-preview" style="<?php echo empty($logo_url) ? 'display:none;' : ''; ?>">
                                                        <?php if ($logo_url) : ?>
                                                            <img src="<?php echo esc_url($logo_url); ?>" alt="">
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="sb-er-logo-buttons">
                                                        <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm" id="upload-logo-btn"><?php esc_html_e('Select Logo', 'wpswitchboard'); ?></button>
                                                        <button type="button" class="sb-module-button sb-module-button-sm" id="remove-logo-btn" style="<?php echo empty($logo_url) ? 'display:none;' : ''; ?>"><?php esc_html_e('Remove', 'wpswitchboard'); ?></button>
                                                    </div>
                                                </div>
                                                <span class="sb-er-field-help"><?php esc_html_e('Recommended: 200x50 pixels', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Company Name', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <input type="text" name="setting_company_name" value="<?php echo esc_attr($settings['company_name']); ?>" placeholder="<?php echo esc_attr(get_bloginfo('name')); ?>">
                                                <span class="sb-er-field-help"><?php esc_html_e('Leave empty to use site name', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Primary Color', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control sb-er-color-field">
                                                <input type="color" id="setting_primary_color_picker" value="<?php echo esc_attr($settings['primary_color']); ?>">
                                                <input type="text" name="setting_primary_color" id="setting_primary_color" value="<?php echo esc_attr($settings['primary_color']); ?>" placeholder="#2271b1" maxlength="7">
                                            </div>
                                        </div>

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Footer Text', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <textarea name="setting_footer_text" rows="2" placeholder="<?php esc_attr_e('Powered by WP Switchboard', 'wpswitchboard'); ?>"><?php echo esc_textarea($settings['footer_text']); ?></textarea>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Schedule -->
                                    <div class="sb-er-settings-section">
                                        <h3 class="sb-er-settings-section-title"><?php esc_html_e('Schedule', 'wpswitchboard'); ?></h3>
                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Enable Reports', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <label class="sb-module-toggle">
                                                    <input type="checkbox" name="setting_enabled" value="1" <?php checked($settings['enabled'], true); ?>>
                                                    <span class="sb-module-toggle-slider"></span>
                                                </label>
                                                <span class="sb-er-field-help"><?php esc_html_e('Enable scheduled email reports', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Frequency', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <select name="setting_schedule" id="setting_schedule">
                                                    <option value="weekly" <?php selected($settings['schedule'], 'weekly'); ?>><?php esc_html_e('Weekly', 'wpswitchboard'); ?></option>
                                                    <option value="monthly" <?php selected($settings['schedule'], 'monthly'); ?>><?php esc_html_e('Monthly', 'wpswitchboard'); ?></option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="sb-er-field day-of-week-row" style="<?php echo $settings['schedule'] !== 'weekly' ? 'display:none;' : ''; ?>">
                                            <label class="sb-er-field-label"><?php esc_html_e('Day of Week', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <select name="setting_day_of_week">
                                                    <?php foreach ($days_of_week as $value => $label) : ?>
                                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($settings['day_of_week'], $value); ?>><?php echo esc_html($label); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="sb-er-field day-of-month-row" style="<?php echo $settings['schedule'] !== 'monthly' ? 'display:none;' : ''; ?>">
                                            <label class="sb-er-field-label"><?php esc_html_e('Day of Month', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <select name="setting_day_of_month">
                                                    <?php for ($i = 1; $i <= 28; $i++) : ?>
                                                        <option value="<?php echo esc_attr($i); ?>" <?php selected($settings['day_of_month'], $i); ?>><?php echo esc_html($i); ?></option>
                                                    <?php endfor; ?>
                                                </select>
                                                <span class="sb-er-field-help"><?php esc_html_e('Days 29-31 not available for all months', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Time', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <input type="time" name="setting_time" value="<?php echo esc_attr($settings['time']); ?>">
                                                <span class="sb-er-field-help"><?php esc_html_e('In your site timezone', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Report Period', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <select name="setting_report_period">
                                                    <option value="last_7_days" <?php selected($settings['report_period'], 'last_7_days'); ?>><?php esc_html_e('Last 7 Days', 'wpswitchboard'); ?></option>
                                                    <option value="last_30_days" <?php selected($settings['report_period'], 'last_30_days'); ?>><?php esc_html_e('Last 30 Days', 'wpswitchboard'); ?></option>
                                                    <option value="last_month" <?php selected($settings['report_period'], 'last_month'); ?>><?php esc_html_e('Previous Month', 'wpswitchboard'); ?></option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Delivery Mode -->
                                    <div class="sb-er-settings-section">
                                        <h3 class="sb-er-settings-section-title"><?php esc_html_e('Delivery Mode', 'wpswitchboard'); ?></h3>
                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Email Mode', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <select name="setting_delivery_mode" id="setting_delivery_mode">
                                                    <option value="combined" <?php selected($settings['delivery_mode'] ?? 'combined', 'combined'); ?>><?php esc_html_e('Combined - All sections in one email', 'wpswitchboard'); ?></option>
                                                    <option value="separate" <?php selected($settings['delivery_mode'] ?? 'combined', 'separate'); ?>><?php esc_html_e('Separate - Each section as own email', 'wpswitchboard'); ?></option>
                                                </select>
                                                <span class="sb-er-field-help"><?php esc_html_e('Combined sends one email with all sections. Separate sends individual emails per section.', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-field sb-er-global-recipients" id="global-recipients-wrapper" style="<?php echo ($settings['delivery_mode'] ?? 'combined') !== 'combined' ? 'display:none;' : ''; ?>">
                                            <label class="sb-er-field-label"><?php esc_html_e('Send To', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <select name="setting_global_recipients_type" id="setting_global_recipients_type">
                                                    <option value="admin" <?php selected($settings['global_recipients_type'] ?? 'admin', 'admin'); ?>>
                                                        <?php echo esc_html(sprintf(__('Admin (%s)', 'wpswitchboard'), $admin_email)); ?>
                                                    </option>
                                                    <option value="custom" <?php selected($settings['global_recipients_type'] ?? 'admin', 'custom'); ?>>
                                                        <?php esc_html_e('Custom Recipients', 'wpswitchboard'); ?>
                                                    </option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="sb-er-field sb-er-global-recipients sb-er-global-custom-recipients" id="global-custom-recipients-wrapper" style="<?php echo (($settings['delivery_mode'] ?? 'combined') !== 'combined' || ($settings['global_recipients_type'] ?? 'admin') !== 'custom') ? 'display:none;' : ''; ?>">
                                            <label class="sb-er-field-label"><?php esc_html_e('Recipients', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <textarea name="setting_global_custom_recipients" rows="3" placeholder="<?php esc_attr_e('Enter email addresses, one per line', 'wpswitchboard'); ?>"><?php echo esc_textarea($settings['global_custom_recipients'] ?? ''); ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Section Panels (hidden by default, shown when section selected) -->
                    <?php foreach ($sections as $section_id => $section) :
                        $section_config = $section_settings[$section_id] ?? [
                            'enabled'           => false,
                            'recipients_type'   => 'admin',
                            'custom_recipients' => '',
                        ];
                        $is_available = !empty($section['available']);
                        ?>
                        <div class="sb-er-panel sb-er-section-panel" id="section-panel-<?php echo esc_attr($section_id); ?>" style="display: none;" data-section="<?php echo esc_attr($section_id); ?>">
                            <!-- Section Config Card -->
                            <div class="sb-module-card">
                                <div class="sb-module-card-header">
                                    <div class="sb-module-card-header-left">
                                        <h2 class="sb-module-card-title"><?php echo esc_html($section['title']); ?></h2>
                                        <p class="sb-module-card-desc"><?php echo esc_html($section['description'] ?? ''); ?></p>
                                    </div>
                                </div>
                                <div class="sb-module-card-body">
                                    <?php if ($is_available) : ?>
                                        <!-- Hidden field to ensure section exists in POST even when checkbox unchecked -->
                                        <input type="hidden" name="section_settings[<?php echo esc_attr($section_id); ?>][_exists]" value="1">

                                        <div class="sb-er-field">
                                            <label class="sb-er-field-label"><?php esc_html_e('Include in Reports', 'wpswitchboard'); ?></label>
                                            <div class="sb-er-field-control">
                                                <label class="sb-module-toggle">
                                                    <input type="checkbox"
                                                           name="section_settings[<?php echo esc_attr($section_id); ?>][enabled]"
                                                           value="1"
                                                           <?php checked(!empty($section_config['enabled'])); ?>>
                                                    <span class="sb-module-toggle-slider"></span>
                                                </label>
                                                <span class="sb-er-field-help"><?php esc_html_e('Include this section in email reports', 'wpswitchboard'); ?></span>
                                            </div>
                                        </div>

                                        <div class="sb-er-section-recipients">
                                            <div class="sb-er-field">
                                                <label class="sb-er-field-label"><?php esc_html_e('Send To', 'wpswitchboard'); ?></label>
                                                <div class="sb-er-field-control">
                                                    <select name="section_settings[<?php echo esc_attr($section_id); ?>][recipients_type]"
                                                            class="sb-er-recipients-type"
                                                            data-section="<?php echo esc_attr($section_id); ?>">
                                                        <option value="admin" <?php selected($section_config['recipients_type'], 'admin'); ?>>
                                                            <?php echo esc_html(sprintf(__('Admin (%s)', 'wpswitchboard'), $admin_email)); ?>
                                                        </option>
                                                        <option value="custom" <?php selected($section_config['recipients_type'], 'custom'); ?>>
                                                            <?php esc_html_e('Custom Recipients', 'wpswitchboard'); ?>
                                                        </option>
                                                    </select>
                                                    <span class="sb-er-field-help"><?php esc_html_e('Only used in Separate delivery mode', 'wpswitchboard'); ?></span>
                                                </div>
                                            </div>

                                            <div class="sb-er-field sb-er-custom-recipients-field"
                                                 id="custom-recipients-field-<?php echo esc_attr($section_id); ?>"
                                                 style="<?php echo $section_config['recipients_type'] !== 'custom' ? 'display:none;' : ''; ?>">
                                                <label class="sb-er-field-label"><?php esc_html_e('Recipients', 'wpswitchboard'); ?></label>
                                                <div class="sb-er-field-control">
                                                    <textarea name="section_settings[<?php echo esc_attr($section_id); ?>][custom_recipients]"
                                                              rows="3"
                                                              placeholder="<?php esc_attr_e('Enter email addresses, one per line', 'wpswitchboard'); ?>"><?php echo esc_textarea($section_config['custom_recipients']); ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    <?php else : ?>
                                        <div class="sb-er-section-unavailable">
                                            <svg class="sb-er-section-unavailable-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" width="24" height="24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                                            </svg>
                                            <p><?php esc_html_e('This section is not available. Enable the corresponding module to use it.', 'wpswitchboard'); ?></p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Section Preview Card -->
                            <?php if ($is_available) : ?>
                            <div class="sb-module-card" style="margin-top: 16px;">
                                <div class="sb-module-card-header">
                                    <div class="sb-module-card-header-left">
                                        <h2 class="sb-module-card-title"><?php esc_html_e('Section Preview', 'wpswitchboard'); ?></h2>
                                        <p class="sb-module-card-desc"><?php esc_html_e('Preview how this section will appear in the email', 'wpswitchboard'); ?></p>
                                    </div>
                                    <div class="sb-module-card-header-right">
                                        <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm sb-er-refresh-preview" data-section="<?php echo esc_attr($section_id); ?>">
                                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="14" height="14" style="margin-right: 4px;">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                            </svg>
                                            <?php esc_html_e('Refresh', 'wpswitchboard'); ?>
                                        </button>
                                    </div>
                                </div>
                                <div class="sb-module-card-body" style="padding: 0;">
                                    <div class="sb-er-preview-frame sb-er-section-preview" data-section="<?php echo esc_attr($section_id); ?>">
                                        <div class="sb-er-preview-placeholder">
                                            <span><?php esc_html_e('Click Refresh to load preview', 'wpswitchboard'); ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>

                    <?php if (empty($sections)) : ?>
                        <div class="sb-module-card">
                            <div class="sb-module-card-body">
                                <div class="sb-module-empty">
                                    <div class="sb-module-empty-icon"></div>
                                    <p class="sb-module-empty-desc"><?php esc_html_e('No report sections available. Enable modules like Lean Analytics, Activity Log, etc. to see sections here.', 'wpswitchboard'); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Footer Actions -->
            <div class="sb-module-card" style="margin-top: 24px;">
                <div class="sb-module-card-footer">
                    <div id="email-feedback" class="sb-er-feedback" style="display:none;"></div>
                    <div class="sb-module-button-group">
                        <?php
                        // Determine who receives test email
                        $test_recipients_label = '';
                        if ($settings['delivery_mode'] === 'combined') {
                            $test_recipients_label = $settings['global_recipients_type'] === 'custom' && !empty($settings['global_custom_recipients'])
                                ? __('Sends to custom recipients', 'wpswitchboard')
                                : sprintf(__('Sends to %s', 'wpswitchboard'), get_option('admin_email'));
                        } else {
                            $test_recipients_label = __('Sends to configured section recipients', 'wpswitchboard');
                        }
                        ?>
                        <button type="button" class="sb-module-button" id="send-test-btn" title="<?php echo esc_attr($test_recipients_label); ?>">
                            <?php esc_html_e('Send Test', 'wpswitchboard'); ?>
                        </button>
                        <button type="button" class="sb-module-button sb-module-button-secondary" id="send-now-btn"><?php esc_html_e('Send Now', 'wpswitchboard'); ?></button>
                        <button type="submit" class="sb-module-button sb-module-button-primary"><?php esc_html_e('Save Settings', 'wpswitchboard'); ?></button>
                    </div>
                </div>
            </div>
        </form>
        <?php
    }

    /**
     * Render preview tab
     */
    private function render_preview_tab($settings, $sections) {
        ?>
        <div class="sb-module-card">
            <div class="sb-module-card-header">
                <div class="sb-module-card-header-left">
                    <h2 class="sb-module-card-title"><?php esc_html_e('Report Preview', 'wpswitchboard'); ?></h2>
                    <p class="sb-module-card-desc"><?php esc_html_e('Preview how your email report will look', 'wpswitchboard'); ?></p>
                </div>
                <div class="sb-module-card-header-right">
                    <button type="button" class="sb-module-button sb-module-button-secondary" id="refresh-preview-btn"><?php esc_html_e('Refresh', 'wpswitchboard'); ?></button>
                </div>
            </div>
            <div class="sb-module-card-body" style="padding: 0;">
                <div class="sb-er-preview-frame" id="preview-frame">
                    <div class="sb-er-preview-loading">
                        <span class="spinner is-active"></span>
                        <span><?php esc_html_e('Loading preview...', 'wpswitchboard'); ?></span>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render history tab
     */
    private function render_history_tab() {
        // Get sections from registry
        $registry = class_exists('Switchboard_Report_Registry') ? Switchboard_Report_Registry::get_instance() : null;
        $sections = $registry ? $registry->get_sections(true) : [];
        ?>
        <div class="sb-er-layout">
            <!-- LEFT SIDEBAR: Section Filters -->
            <div class="sb-er-sidebar">
                <div class="sb-module-card">
                    <div class="sb-module-card-header">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Report Sections', 'wpswitchboard'); ?></h2>
                    </div>
                    <div class="sb-module-card-body">
                        <div class="sb-er-sections-list">
                            <button type="button" class="sb-er-history-filter active" data-filter="all" data-section="">
                                <span class="sb-er-section-item-name"><?php esc_html_e('All Sections', 'wpswitchboard'); ?></span>
                                <span class="sb-er-filter-count" id="count-all">-</span>
                            </button>
                            <?php foreach ($sections as $section_id => $section) :
                                if (empty($section['available'])) continue;
                            ?>
                                <button type="button" class="sb-er-history-filter" data-filter="section" data-section="<?php echo esc_attr($section_id); ?>">
                                    <span class="sb-er-section-item-name"><?php echo esc_html($section['title']); ?></span>
                                    <span class="sb-er-filter-count" id="count-<?php echo esc_attr($section_id); ?>">-</span>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Status Filters -->
                <div class="sb-module-card" style="margin-top: 16px;">
                    <div class="sb-module-card-header">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Status', 'wpswitchboard'); ?></h2>
                    </div>
                    <div class="sb-module-card-body">
                        <div class="sb-er-sections-list">
                            <button type="button" class="sb-er-status-filter active" data-status="all">
                                <span class="sb-er-section-item-name"><?php esc_html_e('All', 'wpswitchboard'); ?></span>
                            </button>
                            <button type="button" class="sb-er-status-filter" data-status="sent">
                                <span class="sb-er-section-item-name"><?php esc_html_e('Sent', 'wpswitchboard'); ?></span>
                                <span class="sb-er-filter-count sb-er-filter-count-success" id="count-sent">-</span>
                            </button>
                            <button type="button" class="sb-er-status-filter" data-status="failed">
                                <span class="sb-er-section-item-name"><?php esc_html_e('Failed', 'wpswitchboard'); ?></span>
                                <span class="sb-er-filter-count sb-er-filter-count-error" id="count-failed">-</span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Quick Stats -->
                <div class="sb-module-card" style="margin-top: 16px;">
                    <div class="sb-module-card-header">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Stats', 'wpswitchboard'); ?></h2>
                    </div>
                    <div class="sb-module-card-body">
                        <div class="sb-er-history-stats">
                            <div class="sb-er-history-stat">
                                <span class="sb-er-history-stat-label"><?php esc_html_e('Total Sent', 'wpswitchboard'); ?></span>
                                <span class="sb-er-history-stat-value" id="stat-total-sent">-</span>
                            </div>
                            <div class="sb-er-history-stat">
                                <span class="sb-er-history-stat-label"><?php esc_html_e('Last Report', 'wpswitchboard'); ?></span>
                                <span class="sb-er-history-stat-value" id="stat-last-report">-</span>
                            </div>
                            <div class="sb-er-history-stat">
                                <span class="sb-er-history-stat-label"><?php esc_html_e('Success Rate', 'wpswitchboard'); ?></span>
                                <span class="sb-er-history-stat-value" id="stat-success-rate">-</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- MAIN CONTENT: History Table -->
            <div class="sb-er-main">
                <div class="sb-module-card">
                    <div class="sb-module-card-header">
                        <div class="sb-module-card-header-left">
                            <h2 class="sb-module-card-title" id="history-title"><?php esc_html_e('All Reports', 'wpswitchboard'); ?></h2>
                            <p class="sb-module-card-desc" id="history-desc"><?php esc_html_e('View previously sent reports', 'wpswitchboard'); ?></p>
                        </div>
                        <div class="sb-module-card-header-right">
                            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm" id="clear-history-btn">
                                <?php esc_html_e('Clear All', 'wpswitchboard'); ?>
                            </button>
                        </div>
                    </div>
                    <div class="sb-module-card-body" style="padding: 0;">
                        <div class="sb-module-table-wrapper">
                            <table class="sb-module-table" id="report-history-table">
                                <thead>
                                    <tr>
                                        <th><?php esc_html_e('Date', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Type', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Recipients', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Period', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Status', 'wpswitchboard'); ?></th>
                                        <th style="width: 80px;"><?php esc_html_e('Actions', 'wpswitchboard'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="report-history-body">
                                    <tr>
                                        <td colspan="6">
                                            <div class="sb-er-empty-state">
                                                <div class="sb-er-empty-state-icon">
                                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="48" height="48">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                                    </svg>
                                                </div>
                                                <p class="sb-er-empty-state-title"><?php esc_html_e('Loading...', 'wpswitchboard'); ?></p>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="sb-module-card-footer">
                        <span id="history-page-info" class="sb-er-page-info">-</span>
                        <div class="sb-er-pagination">
                            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm" id="history-prev" disabled>
                                <?php esc_html_e('Previous', 'wpswitchboard'); ?>
                            </button>
                            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm" id="history-next">
                                <?php esc_html_e('Next', 'wpswitchboard'); ?>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render settings for module settings page
     */
    public function render_settings($settings = []) {
        $current_settings = $this->get_settings();
        ?>
        <input type="hidden" name="module" value="email-reports">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Email Reports', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;">
                <?php esc_html_e('Send scheduled email reports with analytics, security, and site health data. Configure detailed settings on the dedicated settings page.', 'wpswitchboard'); ?>
            </p>
        </div>

        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-email-reports')); ?>" class="button button-primary">
                <?php esc_html_e('Configure Email Reports', 'wpswitchboard'); ?>
            </a>
        </p>

        <?php if ($current_settings['enabled']) : ?>
            <p class="description" style="margin-top: 12px; color: #00a32a;">
                <?php
                $next_scheduled = wp_next_scheduled('switchboard_send_' . $current_settings['schedule'] . '_report');
                if ($next_scheduled) {
                    echo esc_html(sprintf(
                        __('Next report scheduled for: %s', 'wpswitchboard'),
                        wp_date(get_option('date_format') . ' ' . get_option('time_format'), $next_scheduled)
                    ));
                }
                ?>
            </p>
        <?php else : ?>
            <p class="description" style="margin-top: 12px;">
                <?php esc_html_e('Reports are currently disabled.', 'wpswitchboard'); ?>
            </p>
        <?php endif; ?>
        <?php
    }

    /**
     * Get date range based on period setting
     */
    private function get_date_range($period = null) {
        if ($period === null) {
            $settings = $this->get_settings();
            $period = $settings['report_period'] ?? 'last_7_days';
        }

        $today = current_time('Y-m-d');

        switch ($period) {
            case 'last_30_days':
                return [
                    'from'  => date('Y-m-d', strtotime('-30 days', strtotime($today))),
                    'to'    => $today,
                    'label' => sprintf(
                        __('%s - %s', 'wpswitchboard'),
                        wp_date(get_option('date_format'), strtotime('-30 days', strtotime($today))),
                        wp_date(get_option('date_format'), strtotime($today))
                    ),
                ];

            case 'last_month':
                $first_of_last_month = date('Y-m-01', strtotime('first day of last month'));
                $last_of_last_month = date('Y-m-t', strtotime('last day of last month'));
                return [
                    'from'  => $first_of_last_month,
                    'to'    => $last_of_last_month,
                    'label' => wp_date('F Y', strtotime($first_of_last_month)),
                ];

            case 'last_7_days':
            default:
                return [
                    'from'  => date('Y-m-d', strtotime('-7 days', strtotime($today))),
                    'to'    => $today,
                    'label' => sprintf(
                        __('%s - %s', 'wpswitchboard'),
                        wp_date(get_option('date_format'), strtotime('-7 days', strtotime($today))),
                        wp_date(get_option('date_format'), strtotime($today))
                    ),
                ];
        }
    }

    /**
     * Get human-readable label for next scheduled report
     */
    private function get_next_scheduled_label() {
        $settings = $this->get_settings();

        if (empty($settings['enabled'])) {
            return __('Reports disabled', 'wpswitchboard');
        }

        $schedule = $settings['schedule'] ?? 'weekly';
        $hook = $schedule === 'monthly' ? 'switchboard_send_monthly_report' : 'switchboard_send_weekly_report';
        $next_run = wp_next_scheduled($hook);

        if (!$next_run) {
            return __('Not scheduled', 'wpswitchboard');
        }

        $time_diff = $next_run - time();

        if ($time_diff < HOUR_IN_SECONDS) {
            return __('Next: in less than an hour', 'wpswitchboard');
        } elseif ($time_diff < DAY_IN_SECONDS) {
            $hours = round($time_diff / HOUR_IN_SECONDS);
            return sprintf(_n('Next: in %d hour', 'Next: in %d hours', $hours, 'wpswitchboard'), $hours);
        } else {
            return sprintf(__('Next: %s', 'wpswitchboard'), wp_date(get_option('date_format') . ' ' . get_option('time_format'), $next_run));
        }
    }

    /**
     * Get recipients for a specific section
     *
     * @param string $section_id
     * @return array Email addresses
     */
    private function get_section_recipients($section_id) {
        $settings = $this->get_settings();
        $section_settings = $settings['section_settings'][$section_id] ?? [];
        $recipients = [];

        $recipients_type = $section_settings['recipients_type'] ?? 'admin';

        if ($recipients_type === 'admin') {
            // Send to admin email only
            $recipients[] = get_option('admin_email');
        } elseif ($recipients_type === 'custom') {
            // Send to custom recipients
            if (!empty($section_settings['custom_recipients'])) {
                $lines = preg_split('/\r\n|\r|\n/', $section_settings['custom_recipients']);
                foreach ($lines as $line) {
                    $email = trim($line);
                    if (is_email($email) && !in_array($email, $recipients, true)) {
                        $recipients[] = $email;
                    }
                }
            }

            // If no custom recipients set, fallback to admin
            if (empty($recipients)) {
                $recipients[] = get_option('admin_email');
            }
        }

        return $recipients;
    }

    /**
     * Get all unique recipients across all enabled sections
     * Used for history logging
     *
     * @return array All unique email addresses
     */
    private function get_all_recipients() {
        $settings = $this->get_settings();
        $section_settings = $settings['section_settings'] ?? [];
        $recipients = [];

        foreach ($section_settings as $section_id => $config) {
            if (!empty($config['enabled'])) {
                $section_recipients = $this->get_section_recipients($section_id);
                $recipients = array_merge($recipients, $section_recipients);
            }
        }

        return array_unique($recipients);
    }

    /**
     * Get branding settings
     */
    private function get_branding() {
        $settings = $this->get_settings();

        $logo_url = '';
        if (!empty($settings['logo_id'])) {
            $logo_url = wp_get_attachment_image_url($settings['logo_id'], 'medium');
        }

        return [
            'logo_url'      => $logo_url,
            'company_name'  => !empty($settings['company_name']) ? $settings['company_name'] : get_bloginfo('name'),
            'primary_color' => $settings['primary_color'] ?? '#2271b1',
            'footer_text'   => !empty($settings['footer_text']) ? $settings['footer_text'] : __('Powered by WP Switchboard', 'wpswitchboard'),
        ];
    }

    /**
     * Get enabled section IDs
     */
    private function get_enabled_section_ids() {
        $settings = $this->get_settings();
        $enabled = [];

        if (!empty($settings['section_settings']) && is_array($settings['section_settings'])) {
            foreach ($settings['section_settings'] as $section_id => $config) {
                if (!empty($config['enabled'])) {
                    $enabled[] = $section_id;
                }
            }
        }

        return $enabled;
    }

    /**
     * Group sections by recipient for sending separate emails
     *
     * @return array [email_key => ['recipients' => [], 'sections' => []]]
     */
    private function get_sections_grouped_by_recipient() {
        $settings = $this->get_settings();
        $section_settings = $settings['section_settings'] ?? [];
        $groups = [];

        foreach ($section_settings as $section_id => $config) {
            if (empty($config['enabled'])) {
                continue;
            }

            $recipients = $this->get_section_recipients($section_id);

            // Create a unique key for this recipient set
            sort($recipients);
            $recipient_key = md5(implode(',', $recipients));

            if (!isset($groups[$recipient_key])) {
                $groups[$recipient_key] = [
                    'recipients' => $recipients,
                    'sections'   => [],
                ];
            }

            $groups[$recipient_key]['sections'][] = $section_id;
        }

        return $groups;
    }

    /**
     * Generate report HTML
     */
    public function generate_report_html($date_range = null, $section_ids = null) {
        if ($date_range === null) {
            $date_range = $this->get_date_range();
        }

        if ($section_ids === null) {
            $section_ids = $this->get_enabled_section_ids();
        }

        $branding = $this->get_branding();
        $settings = $this->get_settings();

        // Get section data
        $registry = class_exists('Switchboard_Report_Registry') ? Switchboard_Report_Registry::get_instance() : null;
        $sections_data = [];

        if ($registry) {
            $registry->maybe_init();
            $sections_data = $registry->get_sections_data($section_ids, $date_range);
        }

        // Determine report title based on schedule
        $schedule = $settings['schedule'] ?? 'weekly';
        $report_title = $schedule === 'monthly'
            ? __('Monthly Site Report', 'wpswitchboard')
            : __('Weekly Site Report', 'wpswitchboard');

        // Generate HTML using output buffering
        ob_start();
        $this->render_email_template([
            'site_name'     => get_bloginfo('name'),
            'site_url'      => home_url(),
            'dashboard_url' => admin_url('admin.php?page=switchboard'),
            'report_title'  => $report_title,
            'date_range'    => $date_range,
            'branding'      => $branding,
            'sections'      => $sections_data,
        ]);
        return ob_get_clean();
    }

    /**
     * Render email template
     */
    private function render_email_template($data) {
        $site_name     = $data['site_name'];
        $site_url      = $data['site_url'];
        $dashboard_url = $data['dashboard_url'];
        $report_title  = $data['report_title'];
        $date_range    = $data['date_range'];
        $branding      = $data['branding'];
        $sections      = $data['sections'];

        // Check if custom template exists
        $template_path = SWITCHBOARD_PATH . 'assets/email-reports/email-template.php';
        if (file_exists($template_path)) {
            include $template_path;
            return;
        }

        // Default inline template
        $primary_color = esc_attr($branding['primary_color']);
        ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html($report_title); ?></title>
</head>
<body style="margin: 0; padding: 0; background-color: #f4f4f4; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;">
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f4f4f4;">
        <tr>
            <td style="padding: 20px 0;">
                <table role="presentation" width="600" cellspacing="0" cellpadding="0" style="margin: 0 auto; max-width: 600px;">
                    <!-- Header -->
                    <tr>
                        <td style="background-color: <?php echo $primary_color; ?>; padding: 30px; text-align: center; border-radius: 8px 8px 0 0;">
                            <?php if (!empty($branding['logo_url'])) : ?>
                                <img src="<?php echo esc_url($branding['logo_url']); ?>" alt="<?php echo esc_attr($branding['company_name']); ?>" style="max-width: 200px; max-height: 60px; margin-bottom: 10px;">
                            <?php endif; ?>
                            <h1 style="color: #ffffff; margin: 0; font-size: 24px; font-weight: 600;"><?php echo esc_html($branding['company_name']); ?></h1>
                        </td>
                    </tr>

                    <!-- Report Title -->
                    <tr>
                        <td style="background-color: #ffffff; padding: 30px; text-align: center; border-bottom: 1px solid #e0e0e0;">
                            <h2 style="color: #1d2327; margin: 0 0 10px; font-size: 22px;"><?php echo esc_html($report_title); ?></h2>
                            <p style="color: #646970; margin: 0; font-size: 14px;"><?php echo esc_html($date_range['label']); ?></p>
                        </td>
                    </tr>

                    <!-- Sections -->
                    <?php if (!empty($sections)) : ?>
                        <?php foreach ($sections as $section_id => $section) : ?>
                            <tr>
                                <td style="background-color: #ffffff; padding: 25px 30px; border-bottom: 1px solid #e0e0e0;">
                                    <h3 style="color: <?php echo $primary_color; ?>; margin: 0 0 15px; font-size: 16px; text-transform: uppercase; letter-spacing: 0.5px;">
                                        <?php echo esc_html($section['title']); ?>
                                    </h3>
                                    <?php $this->render_section_content($section_id, $section['data'], $branding); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <tr>
                            <td style="background-color: #ffffff; padding: 40px 30px; text-align: center;">
                                <p style="color: #646970; margin: 0;"><?php esc_html_e('No report data available for this period.', 'wpswitchboard'); ?></p>
                            </td>
                        </tr>
                    <?php endif; ?>

                    <!-- CTA Button -->
                    <tr>
                        <td style="background-color: #ffffff; padding: 30px; text-align: center;">
                            <a href="<?php echo esc_url($dashboard_url); ?>" style="display: inline-block; background-color: <?php echo $primary_color; ?>; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: 500;">
                                <?php esc_html_e('View Dashboard', 'wpswitchboard'); ?>
                            </a>
                        </td>
                    </tr>

                    <!-- Footer -->
                    <tr>
                        <td style="background-color: #f0f0f1; padding: 20px 30px; text-align: center; border-radius: 0 0 8px 8px;">
                            <p style="color: #646970; margin: 0 0 10px; font-size: 13px;"><?php echo esc_html($branding['footer_text']); ?></p>
                            <p style="color: #646970; margin: 0; font-size: 12px;">
                                <a href="<?php echo esc_url($site_url); ?>" style="color: <?php echo $primary_color; ?>; text-decoration: none;"><?php echo esc_html($site_url); ?></a>
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
        <?php
    }

    /**
     * Render section content based on section ID
     */
    private function render_section_content($section_id, $data, $branding = null) {
        if (empty($data)) {
            echo '<p style="color: #646970; margin: 0;">' . esc_html__('No data available.', 'wpswitchboard') . '</p>';
            return;
        }

        // Ensure branding is available for templates
        if ($branding === null) {
            $branding = $this->get_branding();
        }

        // Check for custom section template
        $template_path = SWITCHBOARD_PATH . 'assets/email-reports/sections/' . $section_id . '.php';
        if (file_exists($template_path)) {
            include $template_path;
            return;
        }

        // Default rendering based on common data structures
        $this->render_default_section_content($data);
    }

    /**
     * Render default section content
     */
    private function render_default_section_content($data) {
        $settings = $this->get_settings();
        $primary_color = esc_attr($settings['primary_color'] ?? '#2271b1');

        // Handle overview/stats data
        $stats_keys = ['pageviews', 'visits', 'visitors', 'unique_visitors', 'bounce_rate', 'total_events', 'failed_logins', 'lockouts', 'total_404s'];
        $has_stats = false;

        echo '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 15px;">';
        echo '<tr>';

        $stat_count = 0;
        foreach ($stats_keys as $key) {
            if (isset($data[$key])) {
                $has_stats = true;
                $value = $data[$key];
                $label = ucwords(str_replace('_', ' ', $key));

                if ($key === 'bounce_rate') {
                    $value = number_format($value, 1) . '%';
                } elseif (is_numeric($value)) {
                    $value = number_format($value);
                }

                echo '<td style="text-align: center; padding: 10px; background-color: #f9f9f9; border-radius: 4px;">';
                echo '<div style="font-size: 24px; font-weight: 600; color: ' . $primary_color . ';">' . esc_html($value) . '</div>';
                echo '<div style="font-size: 12px; color: #646970; text-transform: uppercase;">' . esc_html($label) . '</div>';
                echo '</td>';

                $stat_count++;
                if ($stat_count >= 4) break;
            }
        }

        echo '</tr>';
        echo '</table>';

        // Handle list/table data
        $list_keys = ['top_pages', 'top_posts', 'top_referrers', 'top_404_urls', 'recent_events', 'critical_events'];

        foreach ($list_keys as $key) {
            if (!empty($data[$key]) && is_array($data[$key])) {
                $label = ucwords(str_replace('_', ' ', $key));
                echo '<h4 style="color: #1d2327; margin: 15px 0 10px; font-size: 14px;">' . esc_html($label) . '</h4>';
                echo '<table role="presentation" width="100%" cellspacing="0" cellpadding="8" style="font-size: 13px;">';

                $count = 0;
                foreach ($data[$key] as $item) {
                    if ($count >= 5) break;

                    echo '<tr style="border-bottom: 1px solid #e0e0e0;">';

                    if (is_array($item)) {
                        $title = $item['title'] ?? $item['url'] ?? $item['name'] ?? $item['path'] ?? '';
                        $value = $item['count'] ?? $item['pageviews'] ?? $item['visits'] ?? $item['hits'] ?? '';

                        echo '<td style="color: #1d2327;">' . esc_html($title) . '</td>';
                        if ($value) {
                            echo '<td style="color: #646970; text-align: right; width: 80px;">' . esc_html(number_format($value)) . '</td>';
                        }
                    } else {
                        echo '<td style="color: #1d2327;">' . esc_html($item) . '</td>';
                    }

                    echo '</tr>';
                    $count++;
                }

                echo '</table>';
            }
        }
    }

    /**
     * Send report email
     * Sends separate emails to different recipient groups based on section settings
     */
    public function send_report($report_type = 'scheduled', $schedule_type = null) {
        global $wpdb;

        $settings = $this->get_settings();
        $delivery_mode = $settings['delivery_mode'] ?? 'combined';

        if ($delivery_mode === 'combined') {
            // Combined mode: send ONE email with ALL enabled sections to global recipients
            $enabled_sections = $this->get_enabled_section_ids();

            if (empty($enabled_sections)) {
                return new WP_Error('no_sections', __('No report sections are enabled.', 'wpswitchboard'));
            }

            // Resolve global recipients
            $recipients_type = $settings['global_recipients_type'] ?? 'admin';
            $recipients = [];

            if ($recipients_type === 'custom' && !empty($settings['global_custom_recipients'])) {
                $lines = preg_split('/\r\n|\r|\n/', $settings['global_custom_recipients']);
                foreach ($lines as $line) {
                    $email = trim($line);
                    if (is_email($email) && !in_array($email, $recipients, true)) {
                        $recipients[] = $email;
                    }
                }
            }

            // Fallback to admin email
            if (empty($recipients)) {
                $recipients[] = get_option('admin_email');
            }

            $groups = [
                [
                    'recipients' => $recipients,
                    'sections'   => $enabled_sections,
                ],
            ];
        } else {
            // Separate mode: group sections by per-section recipients
            $groups = $this->get_sections_grouped_by_recipient();
        }

        if (empty($groups)) {
            return new WP_Error('no_sections', __('No report sections are enabled.', 'wpswitchboard'));
        }

        $date_range = $this->get_date_range();
        $branding = $this->get_branding();

        $subject = sprintf(
            '%s - %s',
            $settings['schedule'] === 'monthly' ? __('Monthly Site Report', 'wpswitchboard') : __('Weekly Site Report', 'wpswitchboard'),
            $branding['company_name']
        );

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $branding['company_name'] . ' <' . get_option('admin_email') . '>',
        ];

        $total_sent = 0;
        $total_failed = 0;
        $all_recipients = [];
        $all_sections = [];

        // Send email(s) based on delivery mode groups
        foreach ($groups as $group) {
            $recipients = $group['recipients'];
            $section_ids = $group['sections'];

            if (empty($recipients) || empty($section_ids)) {
                continue;
            }

            // Generate HTML for this group's sections
            $html = $this->generate_report_html($date_range, $section_ids);

            // Send email
            $sent = wp_mail($recipients, $subject, $html, $headers);

            if ($sent) {
                $total_sent++;
            } else {
                $total_failed++;
            }

            // Track for logging
            $all_recipients = array_merge($all_recipients, $recipients);
            $all_sections = array_merge($all_sections, $section_ids);
        }

        // Log the overall report
        $all_recipients = array_unique($all_recipients);
        $all_sections = array_unique($all_sections);

        $log_id = $this->log_report([
            'report_type'     => $report_type,
            'schedule_type'   => $schedule_type ?? $settings['schedule'],
            'recipients'      => $all_recipients,
            'sections'        => $all_sections,
            'date_range_from' => $date_range['from'],
            'date_range_to'   => $date_range['to'],
            'status'          => $total_failed > 0 ? 'failed' : 'sent',
        ]);

        // Update log with sent time
        $wpdb->update(
            $this->table_name,
            [
                'sent_at'       => current_time('mysql'),
                'error_message' => $total_failed > 0
                    ? sprintf(__('%d of %d emails failed to send.', 'wpswitchboard'), $total_failed, $total_sent + $total_failed)
                    : null,
            ],
            ['id' => $log_id],
            ['%s', '%s'],
            ['%d']
        );

        if ($total_failed > 0 && $total_sent === 0) {
            return new WP_Error('send_failed', __('Failed to send email. Check your email settings.', 'wpswitchboard'));
        }

        return [
            'sent'   => $total_sent,
            'failed' => $total_failed,
            'total'  => count($all_recipients),
        ];
    }

    /**
     * Log report to database
     */
    private function log_report($data) {
        global $wpdb;

        $wpdb->insert(
            $this->table_name,
            [
                'report_type'     => $data['report_type'],
                'schedule_type'   => $data['schedule_type'],
                'recipients'      => wp_json_encode($data['recipients']),
                'sections'        => wp_json_encode($data['sections']),
                'date_range_from' => $data['date_range_from'],
                'date_range_to'   => $data['date_range_to'],
                'status'          => $data['status'],
                'created_at'      => current_time('mysql'),
            ],
            ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']
        );

        return $wpdb->insert_id;
    }

    /**
     * Send weekly report (cron handler)
     */
    public function send_weekly_report() {
        $settings = $this->get_settings();

        if (empty($settings['enabled']) || $settings['schedule'] !== 'weekly') {
            return;
        }

        $this->send_report('scheduled', 'weekly');
    }

    /**
     * Send monthly report (cron handler)
     */
    public function send_monthly_report() {
        $settings = $this->get_settings();

        if (empty($settings['enabled']) || $settings['schedule'] !== 'monthly') {
            return;
        }

        $this->send_report('scheduled', 'monthly');
    }

    /**
     * AJAX: Preview report
     */
    public function ajax_preview_report() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        $html = $this->generate_report_html();
        wp_send_json_success(['html' => $html]);
    }

    /**
     * AJAX: Preview a single section
     */
    public function ajax_preview_section() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        $section_input = sanitize_text_field($_POST['section'] ?? '');

        if (empty($section_input)) {
            wp_send_json_error(['message' => __('No section specified.', 'wpswitchboard')]);
        }

        // Get sections from registry
        $registry = class_exists('Switchboard_Report_Registry') ? Switchboard_Report_Registry::get_instance() : null;
        $sections = $registry ? $registry->get_sections(true) : [];

        // Support multiple sections (comma-separated) for combined mode preview
        $section_ids = array_map('sanitize_key', explode(',', $section_input));
        $valid_section_ids = [];

        foreach ($section_ids as $section_id) {
            // Verify this section exists and is available
            if (isset($sections[$section_id]) && !empty($sections[$section_id]['available'])) {
                $valid_section_ids[] = $section_id;
            }
        }

        if (empty($valid_section_ids)) {
            wp_send_json_error(['message' => __('No valid sections available for preview.', 'wpswitchboard')]);
        }

        // Generate HTML for the section(s)
        $html = $this->generate_report_html(null, $valid_section_ids);
        wp_send_json_success(['html' => $html]);
    }

    /**
     * AJAX: Send test email
     */
    public function ajax_send_test() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        // Rate limiting: max 3 test emails per 5 minutes
        $transient_key = 'switchboard_test_email_' . get_current_user_id();
        $attempts = get_transient($transient_key) ?: 0;

        if ($attempts >= 3) {
            wp_send_json_error(['message' => __('Too many test emails. Please wait a few minutes.', 'wpswitchboard')]);
        }

        // Check if there are enabled sections
        $section_ids = $this->get_enabled_section_ids();
        if (empty($section_ids)) {
            wp_send_json_error(['message' => __('No report sections are enabled. Enable at least one section.', 'wpswitchboard')]);
        }

        set_transient($transient_key, $attempts + 1, 5 * MINUTE_IN_SECONDS);

        $result = $this->send_report('test');

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        $count = is_array($result) ? $result['total'] : 1;
        wp_send_json_success([
            'message' => sprintf(
                _n('Test email sent to %d recipient!', 'Test emails sent to %d recipients!', $count, 'wpswitchboard'),
                $count
            ),
        ]);
    }

    /**
     * AJAX: Send report now (manual trigger)
     */
    public function ajax_send_now() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        // Rate limiting: max 5 reports per hour
        $transient_key = 'switchboard_send_now_' . get_current_user_id();
        $attempts = get_transient($transient_key) ?: 0;

        if ($attempts >= 5) {
            wp_send_json_error(['message' => __('Rate limit exceeded. Please wait before sending more reports.', 'wpswitchboard')]);
        }

        // Check if there are enabled sections
        $section_ids = $this->get_enabled_section_ids();
        if (empty($section_ids)) {
            wp_send_json_error(['message' => __('No report sections are enabled. Enable at least one section.', 'wpswitchboard')]);
        }

        set_transient($transient_key, $attempts + 1, HOUR_IN_SECONDS);

        $result = $this->send_report('manual');

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        $count = is_array($result) ? $result['total'] : 1;
        wp_send_json_success([
            'message' => sprintf(
                _n('Report sent to %d recipient!', 'Report sent to %d recipients!', $count, 'wpswitchboard'),
                $count
            ),
        ]);
    }

    /**
     * AJAX: Get history
     */
    public function ajax_get_history() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        global $wpdb;

        $page = intval($_POST['page'] ?? 1);
        $section = sanitize_key($_POST['section'] ?? '');
        $status = sanitize_key($_POST['status'] ?? 'all');
        $per_page = 20;
        $offset = ($page - 1) * $per_page;

        // Build WHERE clauses
        $where_parts = [];
        $where_params = [];

        if ($status === 'sent') {
            $where_parts[] = "status = 'sent'";
        } elseif ($status === 'failed') {
            $where_parts[] = "status = 'failed'";
        }

        if (!empty($section)) {
            // Filter by section - sections are stored as JSON array
            $where_parts[] = "sections LIKE %s";
            $where_params[] = '%"' . $section . '"%';
        }

        $where = !empty($where_parts) ? 'WHERE ' . implode(' AND ', $where_parts) : '';

        if (!empty($where_params)) {
            $logs = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM {$this->table_name} {$where} ORDER BY created_at DESC LIMIT %d OFFSET %d",
                array_merge($where_params, [$per_page, $offset])
            ));
            $total = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$this->table_name} {$where}",
                $where_params
            ));
        } else {
            $logs = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM {$this->table_name} {$where} ORDER BY created_at DESC LIMIT %d OFFSET %d",
                $per_page,
                $offset
            ));
            $total = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} {$where}");
        }

        // Get counts for status filters
        $counts = [
            'all'    => intval($wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}")),
            'sent'   => intval($wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} WHERE status = 'sent'")),
            'failed' => intval($wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} WHERE status = 'failed'")),
        ];

        // Get section counts
        $registry = class_exists('Switchboard_Report_Registry') ? Switchboard_Report_Registry::get_instance() : null;
        $available_sections = $registry ? $registry->get_sections(true) : [];
        $section_counts = [];
        foreach ($available_sections as $sec_id => $sec_data) {
            $section_counts[$sec_id] = intval($wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$this->table_name} WHERE sections LIKE %s",
                '%"' . $sec_id . '"%'
            )));
        }
        $counts['sections'] = $section_counts;

        // Get stats
        $last_sent = $wpdb->get_var("SELECT created_at FROM {$this->table_name} WHERE status = 'sent' ORDER BY created_at DESC LIMIT 1");
        $stats = [
            'total_sent'   => $counts['sent'],
            'last_report'  => $last_sent ? human_time_diff(strtotime($last_sent), time()) . ' ' . __('ago', 'wpswitchboard') : __('Never', 'wpswitchboard'),
            'success_rate' => $counts['all'] > 0 ? round(($counts['sent'] / $counts['all']) * 100) . '%' : '0%',
        ];

        $items = [];
        foreach ($logs as $log) {
            $recipients = json_decode($log->recipients, true) ?: [];
            $timestamp = strtotime($log->created_at);

            // Format relative date
            $relative_date = human_time_diff($timestamp, time());
            if ($timestamp > time() - DAY_IN_SECONDS) {
                $relative_date = sprintf(__('%s ago', 'wpswitchboard'), $relative_date);
            } elseif ($timestamp > time() - (2 * DAY_IN_SECONDS)) {
                $relative_date = __('Yesterday', 'wpswitchboard');
            } else {
                $relative_date = sprintf(__('%s ago', 'wpswitchboard'), $relative_date);
            }

            // Format period nicely
            $from_date = wp_date(get_option('date_format'), strtotime($log->date_range_from));
            $to_date = wp_date(get_option('date_format'), strtotime($log->date_range_to));
            $period = $from_date . ' → ' . $to_date;

            $items[] = [
                'id'           => $log->id,
                'date'         => $relative_date,
                'date_full'    => wp_date(get_option('date_format') . ' ' . get_option('time_format'), $timestamp),
                'type'         => ucfirst($log->report_type),
                'recipients'   => implode(', ', array_slice($recipients, 0, 2)) . (count($recipients) > 2 ? ' +' . (count($recipients) - 2) : ''),
                'recipient_count' => count($recipients),
                'period'       => $period,
                'status'       => $log->status,
                'status_label' => $log->status === 'sent' ? __('Sent', 'wpswitchboard') : __('Failed', 'wpswitchboard'),
                'error'        => $log->error_message,
            ];
        }

        wp_send_json_success([
            'items'   => $items,
            'total'   => intval($total),
            'pages'   => ceil($total / $per_page),
            'current' => $page,
            'counts'  => $counts,
            'stats'   => $stats,
        ]);
    }

    /**
     * AJAX: Delete history entry
     */
    public function ajax_delete_history() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        $id = intval($_POST['id'] ?? 0);

        if (!$id) {
            wp_send_json_error(['message' => __('Invalid ID.', 'wpswitchboard')]);
        }

        global $wpdb;
        $wpdb->delete($this->table_name, ['id' => $id], ['%d']);

        wp_send_json_success(['message' => __('Entry deleted.', 'wpswitchboard')]);
    }

    /**
     * AJAX: Clear all history
     */
    public function ajax_clear_all_history() {
        check_ajax_referer('switchboard_email_reports', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'wpswitchboard')]);
        }

        global $wpdb;
        $wpdb->query("TRUNCATE TABLE {$this->table_name}");

        wp_send_json_success(['message' => __('All history cleared.', 'wpswitchboard')]);
    }
}

// Initialize module and register with data registry
$switchboard_instance = new SwitchboardEmailReports();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
