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

(function () {
    $alert_manager = Vulnity_Alert_Manager::get_instance();
    $inventory_sync = Vulnity_Inventory_Sync::get_instance();
    $static_security = Vulnity_Static_Security::get_instance();
    $stats = $alert_manager->get_statistics();
    $alerts = $alert_manager->get_alerts(50);
    $config = get_option('vulnity_config');
    if (!is_array($config)) {
        $config = array();
    }
    $config = wp_parse_args($config, array(
        'site_id' => '',
        'paired_at' => '—',
    ));
    $sync_info = $inventory_sync->get_last_sync_info();
    $inventory_summary = $inventory_sync->get_inventory_summary();

    $allowed_tabs = array('dashboard', 'alerts', 'mitigation', 'hardening', 'sync', 'settings');
    $active_tab = (isset($active_tab) && in_array($active_tab, $allowed_tabs, true)) ? $active_tab : 'dashboard';

    $tab_classes = array();
    $tab_visibility = array();

    foreach ($allowed_tabs as $tab_slug) {
        $tab_classes[$tab_slug] = $active_tab === $tab_slug ? ' active' : '';
        $tab_visibility[$tab_slug] = $active_tab === $tab_slug ? '' : ' hidden';
    }

    $unread_alerts = isset($stats['unread_alerts']) ? absint($stats['unread_alerts']) : 0;
    $total_alerts = isset($stats['total_alerts']) ? absint($stats['total_alerts']) : 0;
    $alerts_24h = isset($stats['alerts_24h']) ? absint($stats['alerts_24h']) : 0;
    $severity_counts = isset($stats['severity_counts']) && is_array($stats['severity_counts']) ? array_map('absint', $stats['severity_counts']) : [];
    $inventory_plugins_total = isset($inventory_summary['plugins_total']) ? absint($inventory_summary['plugins_total']) : 0;
    $inventory_plugins_active = isset($inventory_summary['plugins_active']) ? absint($inventory_summary['plugins_active']) : 0;
    $inventory_themes_total = isset($inventory_summary['themes_total']) ? absint($inventory_summary['themes_total']) : 0;
    $inventory_users_total = isset($inventory_summary['users_total']) ? absint($inventory_summary['users_total']) : 0;
    $inventory_plugins_updates = isset($inventory_summary['plugins_updates']) ? absint($inventory_summary['plugins_updates']) : 0;
    $inventory_themes_updates = isset($inventory_summary['themes_updates']) ? absint($inventory_summary['themes_updates']) : 0;
    $inventory_administrators = isset($inventory_summary['administrators']) ? absint($inventory_summary['administrators']) : 0;
    $hardening_settings = $static_security->get_settings();
    $hardening_login_slug = isset($hardening_settings['rename_login_slug']) ? $hardening_settings['rename_login_slug'] : Vulnity_Static_Security::DEFAULT_LOGIN_SLUG;
    $hardening_login_url = home_url('/' . $hardening_login_slug . '/');
    $login_attempt_limit = isset($hardening_settings['login_attempt_limit']) ? absint($hardening_settings['login_attempt_limit']) : 5;
    $login_lockout_minutes = isset($hardening_settings['login_lockout_minutes']) ? absint($hardening_settings['login_lockout_minutes']) : 5;
    $settings_sync_status = isset($sync_info['status']) ? strtolower((string) $sync_info['status']) : 'never';
    $settings_last_sync_text = 'Never';
    if (!empty($sync_info['timestamp'])) {
        $settings_last_sync_ts = strtotime((string) $sync_info['timestamp']);
        if (false !== $settings_last_sync_ts && $settings_last_sync_ts > 0) {
            $settings_last_sync_text = wp_date('M j, Y H:i', $settings_last_sync_ts) . ' (' . human_time_diff($settings_last_sync_ts, current_time('timestamp')) . ' ago)';
        }
    }
    $settings_next_sync_text = 'Not scheduled';
    $settings_next_sync_ts = wp_next_scheduled('vulnity_sync_inventory');
    if ($settings_next_sync_ts) {
        $settings_next_sync_text = wp_date('M j, Y H:i', $settings_next_sync_ts) . ' (in ' . human_time_diff(current_time('timestamp'), $settings_next_sync_ts) . ')';
    }
    $sync_status_label_map = array(
        'never' => 'Never synchronized',
        'success' => 'Synchronized',
        'pending' => 'Synchronizing',
        'failed' => 'Failed',
        'error' => 'Failed',
    );
    $sync_status_css_map = array(
        'never' => 'is-warning',
        'success' => 'is-success',
        'pending' => 'is-info',
        'failed' => 'is-danger',
        'error' => 'is-danger',
    );
    $sync_status_label = isset($sync_status_label_map[$settings_sync_status]) ? $sync_status_label_map[$settings_sync_status] : 'Unknown';
    $sync_status_css = isset($sync_status_css_map[$settings_sync_status]) ? $sync_status_css_map[$settings_sync_status] : 'is-neutral';
    $sync_tracked_assets_total = $inventory_plugins_total + $inventory_themes_total + $inventory_users_total;
    $sync_pending_updates_total = $inventory_plugins_updates + $inventory_themes_updates + (!empty($inventory_summary['wordpress_update']) ? 1 : 0);

    $severity_catalog = array(
        'critical' => array(
            'privilege_escalation',
            'roles.privilege_escalation',
            'plugin_cve',
            'plugin.vuln_match',
            'config.exposed_backup_files',
            'core_integrity_breach',
            'file_security_alert',
            'php_upload',
        ),
        'high' => array(
            'auth.bruteforce',
            'bruteforce_ip',
            'brute_force_alert',
            'users.new_admin_created',
            'new_admin_created',
            'plugin.deactivated_security',
            'security_plugin_disabled',
            'core.update_available_critical',
            'core_security_update',
            'option.siteurl_or_home_changed',
            'siteurl_changed',
            'theme_cve',
            'suspicious_upload',
            'elevated_default_role',
            'user_management_alert',
            'file_editor_alert',
            'core_update_alert',
            'suspicious_query_alert',
        ),
        'medium' => array(
            'auth.success_from_new_ip',
            'login_new_ip',
            'bruteforce_user',
            'password_reset_spike',
            'plugin.installed_or_activated',
            'plugin_activated',
            'file.editor_usage',
            'file_editor_used',
            'file.editor_enabled',
            'restapi.sensitive_route_access',
            'rest_access_no_auth',
            'theme_changed',
            'user_registration_enabled',
            'email_spike',
            'directory_listing',
            'app_password_created',
            'plugin_outdated',
            'theme_outdated',
            'plugin_change_alert',
            'theme_change_alert',
            'scanner_detected_alert',
        ),
        'low' => array(
            'admin_user_exists',
        ),
        'info' => array(
            'user_created',
            'user_deleted',
            'system_notification',
            'heartbeat',
            'site_paired',
            'site_unpaired',
        ),
    );

    $normalize_alert_key = static function ($value) {
        if (!is_scalar($value)) {
            return '';
        }

        $normalized = strtolower(trim((string) $value));

        if ($normalized === '') {
            return '';
        }

        $normalized = preg_replace('/[^a-z0-9]+/', '_', $normalized);

        return trim((string) $normalized, '_');
    };

    $severity_by_type = array();

    foreach ($severity_catalog as $severity => $types) {
        foreach ($types as $type_key) {
            $normalized_type_key = $normalize_alert_key($type_key);
            if ($normalized_type_key !== '') {
                $severity_by_type[$normalized_type_key] = $severity;
            }
        }
    }

    $resolve_alert_severity = static function ($alert) use ($normalize_alert_key, $severity_by_type) {
        $default_severity = isset($alert['severity']) ? strtolower((string) $alert['severity']) : '';

        if (!in_array($default_severity, array('critical', 'high', 'medium', 'low', 'info'), true)) {
            $default_severity = 'info';
        }

        $candidate_types = array();

        if (isset($alert['type'])) {
            $candidate_types[] = $alert['type'];
        }

        if (isset($alert['details']) && is_array($alert['details'])) {
            if (!empty($alert['details']['alert_type'])) {
                $candidate_types[] = $alert['details']['alert_type'];
            }

            if (!empty($alert['details']['action'])) {
                $candidate_types[] = $alert['details']['action'];
            }
        }

        foreach ($candidate_types as $candidate_type) {
            $normalized_candidate = $normalize_alert_key($candidate_type);

            if ($normalized_candidate !== '' && isset($severity_by_type[$normalized_candidate])) {
                return $severity_by_type[$normalized_candidate];
            }
        }

        return $default_severity;
    };
?>

<div class="wrap">
    <!-- Header banner removed -->
    
    <div class="vulnity-tabs">
        <div class="vulnity-tabs-brand"><?php echo esc_html__('Vulnity Security', 'vulnity'); ?></div>
        <div class="vulnity-tabs-nav">
            <button type="button" class="vulnity-tab<?php echo esc_attr($tab_classes['dashboard']); ?>" data-tab="dashboard"><?php echo esc_html__('Dashboard', 'vulnity'); ?></button>
            <button type="button" class="vulnity-tab<?php echo esc_attr($tab_classes['alerts']); ?>" data-tab="alerts"><?php echo esc_html__('Alerts', 'vulnity'); ?></button>
            <button type="button" class="vulnity-tab<?php echo esc_attr($tab_classes['mitigation']); ?>" data-tab="mitigation"><?php echo esc_html__('Mitigation', 'vulnity'); ?></button>
            <button type="button" class="vulnity-tab<?php echo esc_attr($tab_classes['hardening']); ?>" data-tab="hardening"><?php echo esc_html__('Hardening', 'vulnity'); ?></button>
            <button type="button" class="vulnity-tab<?php echo esc_attr($tab_classes['sync']); ?>" data-tab="sync"><?php echo esc_html__('Synchronization', 'vulnity'); ?></button>
            <button type="button" class="vulnity-tab<?php echo esc_attr($tab_classes['settings']); ?>" data-tab="settings"><?php echo esc_html__('Settings', 'vulnity'); ?></button>
        </div>
        <div class="vulnity-tabs-spacer" aria-hidden="true"></div>
    </div>

    <div class="vulnity-tab-content<?php echo esc_attr($tab_classes['dashboard']); ?> vulnity-tab-grid vulnity-dashboard-grid" id="tab-dashboard"<?php echo esc_attr($tab_visibility['dashboard']); ?>>
        <div class="vulnity-content-wide vulnity-span-full">
            <div class="card vulnity-security-overview-card">
                <div class="vulnity-card-header">
                    <h2><?php echo esc_html__('Security overview', 'vulnity'); ?></h2>
                    <p><?php echo esc_html__('Alert volume and severity distribution across your Vulnity site.', 'vulnity'); ?></p>
                </div>
                <div class="vulnity-stats-grid">
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label"><?php echo esc_html__('Total Alerts', 'vulnity'); ?></div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($total_alerts)); ?></div>
                        <span class="vulnity-chip"><?php echo esc_html__('Historical trend', 'vulnity'); ?></span>
                    </div>
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label"><?php echo esc_html__('Last 24 Hours', 'vulnity'); ?></div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($alerts_24h)); ?></div>
                        <span class="vulnity-chip vulnity-chip-info"><?php echo esc_html__('Recent activity', 'vulnity'); ?></span>
                    </div>
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label"><?php echo esc_html__('Critical', 'vulnity'); ?></div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($severity_counts['critical'] ?? 0)); ?></div>
                        <span class="vulnity-chip vulnity-chip-danger"><?php echo esc_html__('Immediate attention', 'vulnity'); ?></span>
                    </div>
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label"><?php echo esc_html__('High', 'vulnity'); ?></div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($severity_counts['high'] ?? 0)); ?></div>
                        <span class="vulnity-chip vulnity-chip-warning"><?php echo esc_html__('Priority review', 'vulnity'); ?></span>
                    </div>
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label"><?php echo esc_html__('Medium', 'vulnity'); ?></div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($severity_counts['medium'] ?? 0)); ?></div>
                        <span class="vulnity-chip vulnity-chip-info"><?php echo esc_html__('Monitoring', 'vulnity'); ?></span>
                    </div>
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label">Low</div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($severity_counts['low'] ?? 0)); ?></div>
                        <span class="vulnity-chip">Basic watch</span>
                    </div>
                    <div class="vulnity-stat-card">
                        <div class="vulnity-stat-label">Info</div>
                        <div class="vulnity-stat-value"><?php echo esc_html(number_format_i18n($severity_counts['info'] ?? 0)); ?></div>
                        <span class="vulnity-chip">Informational</span>
                    </div>
                </div>
            </div>
        </div>

        <?php
        // Calculate delivery stats
        $total_alert_count = count($alerts);
        $sent_count = count(array_filter($alerts, function($a) { return !empty($a['sent_to_siem']); }));
        $failed_count = $total_alert_count - $sent_count;
        $sent_percentage = $total_alert_count > 0 ? round(($sent_count / $total_alert_count) * 100, 1) : 0;
        $failed_percentage = $total_alert_count > 0 ? round(($failed_count / $total_alert_count) * 100, 1) : 0;
        ?>

        <div class="vulnity-section-grid">
        <div class="card vulnity-card-gradient vulnity-delivery-card">
            <div class="vulnity-card-header">
                <div>
                    <h2>Alert Delivery Status</h2>
                    <p>Monitor SIEM event delivery and act quickly on failures.</p>
                </div>
                <span class="vulnity-delivery-pill <?php echo $failed_count > 0 ? 'is-issue' : 'is-healthy'; ?>">
                    <?php echo esc_html(number_format_i18n($sent_percentage, 1)); ?>% delivered
                </span>
            </div>
            <div class="vulnity-delivery-grid">
                <article class="vulnity-delivery-item is-sent">
                    <span class="vulnity-delivery-label">Sent to SIEM</span>
                    <div class="vulnity-delivery-value"><?php echo esc_html(number_format_i18n($sent_count)); ?></div>
                    <span class="vulnity-delivery-percent"><?php echo esc_html(number_format_i18n($sent_percentage, 1)); ?>%</span>
                    <div class="vulnity-delivery-meter" aria-hidden="true">
                        <span style="width: <?php echo esc_attr((string) $sent_percentage); ?>%;"></span>
                    </div>
                </article>

                <article class="vulnity-delivery-item is-failed">
                    <span class="vulnity-delivery-label">Failed / Pending</span>
                    <div class="vulnity-delivery-value"><?php echo esc_html(number_format_i18n($failed_count)); ?></div>
                    <span class="vulnity-delivery-percent"><?php echo esc_html(number_format_i18n($failed_percentage, 1)); ?>%</span>
                    <div class="vulnity-delivery-meter" aria-hidden="true">
                        <span style="width: <?php echo esc_attr((string) $failed_percentage); ?>%;"></span>
                    </div>
                </article>
            </div>

            <?php if ($failed_count > 0): ?>
            <div class="vulnity-inline-callout vulnity-delivery-note">
                <strong>Note:</strong> <?php echo esc_html(number_format_i18n($failed_count)); ?> alerts failed to send.
                <a href="#tab-alerts" onclick="jQuery('.vulnity-tab[data-tab=alerts]').click();">View Alerts Tab</a> to retry.
                Background retry attempts occur every 5 minutes.
            </div>
            <?php endif; ?>
        </div>

        <div class="card vulnity-distribution-card">
            <div class="vulnity-card-header">
                <div>
                    <h2>Alert Distribution (24h)</h2>
                    <p>Understand how recent alerts are distributed by severity.</p>
                </div>
                <span class="vulnity-chip vulnity-chip-info"><?php echo esc_html(number_format_i18n($alerts_24h)); ?> alerts</span>
            </div>
            <div class="vulnity-distribution-list">
                <?php
                $severity_order = array('critical', 'high', 'medium', 'low');
                foreach ($severity_order as $severity):
                    $count = isset($severity_counts[$severity]) ? absint($severity_counts[$severity]) : 0;
                    $percentage = $alerts_24h > 0 ? round(($count / $alerts_24h) * 100, 1) : 0;
                    $severity_class = sanitize_html_class($severity);
                ?>
                    <article class="vulnity-distribution-item">
                        <div class="vulnity-distribution-head">
                            <span class="vulnity-severity-badge vulnity-<?php echo esc_attr($severity_class); ?>">
                                <?php echo esc_html(ucfirst($severity)); ?>
                            </span>
                            <span class="vulnity-distribution-count"><?php echo esc_html(number_format_i18n($count)); ?></span>
                        </div>
                        <div class="vulnity-distribution-meter" aria-hidden="true">
                            <span class="vulnity-<?php echo esc_attr($severity_class); ?>" style="width: <?php echo esc_attr((string) $percentage); ?>%;"></span>
                        </div>
                        <div class="vulnity-distribution-percent"><?php echo esc_html(number_format_i18n($percentage, 1)); ?>%</div>
                    </article>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="card vulnity-card-columns vulnity-system-card">
            <div class="vulnity-card-header">
                <div>
                    <h2>System Status</h2>
                    <p>Review connectivity, synchronization, and active modules.</p>
                </div>
                <span class="vulnity-chip <?php echo ($sync_info['status'] === 'success') ? 'vulnity-chip-info' : 'vulnity-chip-warning'; ?>">
                    <?php echo ($sync_info['status'] === 'success') ? 'Operational' : 'Needs review'; ?>
                </span>
            </div>
            <div class="vulnity-system-grid">
                <div class="vulnity-system-row">
                    <span class="vulnity-system-label">SIEM Connection</span>
                    <span class="vulnity-system-value">
                        <span class="vulnity-status-indicator vulnity-status-connected"></span>
                        Connected
                    </span>
                </div>
                <div class="vulnity-system-row">
                    <span class="vulnity-system-label">Site ID</span>
                    <code class="vulnity-system-code"><?php echo esc_html($config['site_id']); ?></code>
                </div>
                <div class="vulnity-system-row">
                    <span class="vulnity-system-label">Connected Since</span>
                    <span class="vulnity-system-value"><?php echo esc_html($config['paired_at']); ?></span>
                </div>
                <div class="vulnity-system-row">
                    <span class="vulnity-system-label">Last Sync</span>
                    <span class="vulnity-system-value">
                        <?php if ($sync_info['status'] === 'never'): ?>
                            Never synchronized
                        <?php else: ?>
                            <?php echo esc_html(human_time_diff(strtotime($sync_info['timestamp']), current_time('timestamp'))); ?> ago
                            <span class="vulnity-system-sync <?php echo ($sync_info['status'] === 'success') ? 'is-ok' : 'is-error'; ?>">
                                <?php echo ($sync_info['status'] === 'success') ? 'OK' : 'Error'; ?>
                            </span>
                        <?php endif; ?>
                    </span>
                </div>
                <div class="vulnity-system-row">
                    <span class="vulnity-system-label">Detection Modules</span>
                    <span class="vulnity-system-value">10 Active</span>
                </div>
            </div>
        </div>
        </div>
    </div>

    <div class="vulnity-tab-content<?php echo esc_attr($tab_classes['alerts']); ?>" id="tab-alerts"<?php echo esc_attr($tab_visibility['alerts']); ?>>
        <div class="vulnity-alert-controls">
            <button type="button" class="button" onclick="vulnityMarkAllViewed()">Mark All as Viewed</button>
            <button type="button" class="button" onclick="vulnityClearAlerts()">Clear All</button>
            <?php 
            $failed_alerts = array_filter($alerts, function($a) { return !$a['sent_to_siem']; });
            if (count($failed_alerts) > 0): 
            ?>
            <button type="button" class="button button-primary" id="retry-all-failed-btn" onclick="vulnityRetryAllFailedAlerts()">
                Retry All Failed (<?php echo esc_html(number_format_i18n(count($failed_alerts))); ?>)
            </button>
            <?php endif; ?>
        </div>
        
        <?php if (empty($alerts)): ?>
            <div class="vulnity-no-alerts">
                <p>No security alerts detected yet.</p>
            </div>
        <?php else: ?>
            <div class="vulnity-alerts-container">
                <?php foreach ($alerts as $alert): ?>
                    <?php
                    $alert_id = isset($alert['id']) ? $alert['id'] : '';
                    $alert_severity = sanitize_html_class($resolve_alert_severity($alert));
                    $alert_status = isset($alert['status']) ? sanitize_html_class($alert['status']) : '';
                    ?>
                    <div class="vulnity-alert vulnity-alert-<?php echo esc_attr($alert_severity); ?> <?php echo esc_attr($alert_status); ?>" data-alert-id="<?php echo esc_attr($alert_id); ?>">
                        <div class="vulnity-alert-header">
                            <span class="vulnity-alert-title"><?php echo esc_html($alert['title']); ?></span>
                            <span class="vulnity-alert-time"><?php echo esc_html(human_time_diff(strtotime($alert['timestamp']), current_time('timestamp'))); ?> ago</span>
                        </div>
                        <div class="vulnity-alert-message">
                            <?php echo esc_html($alert['message']); ?>
                        </div>
                        <div class="vulnity-alert-details">
                            <details>
                                <summary>View Details</summary>
                                <pre><?php echo esc_html(json_encode($alert['details'], JSON_PRETTY_PRINT)); ?></pre>
                            </details>
                        </div>
                        <div class="vulnity-alert-actions">
                            <?php if ($alert['status'] === 'new'): ?>
                                <button type="button" class="button button-small" onclick="vulnityMarkViewed('<?php echo esc_js($alert_id); ?>')">Mark as Viewed</button>
                            <?php endif; ?>
                            
                            <?php if ($alert['sent_to_siem']): ?>
                                <span class="vulnity-siem-status" title="Sent at: <?php echo esc_attr(isset($alert['sent_at']) ? $alert['sent_at'] : 'Unknown'); ?>">
                                    Sent to SIEM
                                </span>
                            <?php else: ?>
                                <span class="vulnity-siem-status" style="background: #dc3232;">
                                    Not Sent
                                </span>
                                <button type="button" class="button button-small button-primary" id="retry-<?php echo esc_attr($alert_id); ?>" onclick="vulnityRetryAlert('<?php echo esc_js($alert_id); ?>')">
                                    Retry Send
                                </button>
                                <?php if (isset($alert['retry_count']) && $alert['retry_count'] > 0): ?>
                                    <small style="color: #999;">Retries: <?php echo esc_html(number_format_i18n(absint($alert['retry_count']))); ?></small>
                                <?php endif; ?>
                                <?php if (isset($alert['last_error'])): ?>
                                    <small style="color: #dc3232;" title="<?php echo esc_attr($alert['last_error']); ?>">
                                        Error: <?php echo esc_html(substr($alert['last_error'], 0, 50)); ?>...
                                    </small>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <div class="vulnity-tab-content<?php echo esc_attr($tab_classes['mitigation']); ?>" id="tab-mitigation"<?php echo esc_attr($tab_visibility['mitigation']); ?>>
        <?php include vulnity_plugin_path('views/admin-mitigation.php'); ?>
    </div>

    <div class="vulnity-tab-content<?php echo esc_attr($tab_classes['hardening']); ?> vulnity-tab-grid" id="tab-hardening"<?php echo esc_attr($tab_visibility['hardening']); ?>>
        <div class="vulnity-content-wide vulnity-span-full">
            <?php
            $hardening_toggles = array(
                'disable_xmlrpc' => __('XML-RPC', 'vulnity'),
                'restrict_rest_api' => __('REST API', 'vulnity'),
                'rename_login_enabled' => __('Login URL', 'vulnity'),
                'block_user_enumeration' => __('User enumeration', 'vulnity'),
                'protect_common_paths' => __('Common paths', 'vulnity'),
                'limit_login_attempts' => __('Login attempts', 'vulnity'),
                'hide_wp_version' => __('WP Version', 'vulnity'),
            );
            $hardening_enabled = array_filter($hardening_toggles, function ($key) use ($hardening_settings) {
                return !empty($hardening_settings[$key]);
            }, ARRAY_FILTER_USE_KEY);
            $hardening_enabled_count = count($hardening_enabled);
            ?>

            <div class="vulnity-hardening-shell vulnity-span-full">
                <div class="vulnity-section-head vulnity-hardening-config-head">
                    <div>
                        <h2>Hardening</h2>
                        <p class="vulnity-muted">Enable the protections you need. Changes apply immediately.</p>
                    </div>
                    <div class="vulnity-hardening-config-meta">
                        <span class="vulnity-hardening-pill vulnity-hardening-pill--soft">
                            <?php echo esc_html($hardening_enabled_count); ?>/<?php echo esc_html(count($hardening_toggles)); ?> enabled
                        </span>
                        <span class="vulnity-hardening-pill">
                            <span>Login path</span>
                            <code><?php echo esc_html($hardening_login_slug); ?></code>
                        </span>
                    </div>
                </div>
                <?php settings_errors('vulnity_hardening_messages'); ?>
                <div class="vulnity-hardening-config-form">
                    <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=vulnity&tab=hardening')); ?>">
                        <?php wp_nonce_field('vulnity_hardening_save', 'vulnity_hardening_nonce'); ?>
                        <?php $static_security->render_settings_fields($hardening_settings, $hardening_login_slug, $hardening_login_url); ?>
                        <?php submit_button(__('Save Changes', 'vulnity')); ?>
                    </form>
                </div>
            </div>
        </div>
    </div>
        <div class="vulnity-tab-content<?php echo esc_attr($tab_classes['sync']); ?> vulnity-tab-grid" id="tab-sync"<?php echo esc_attr($tab_visibility['sync']); ?>>
        <div class="vulnity-sync-shell">
            <section class="card vulnity-sync-panel">
                <header class="vulnity-sync-header">
                    <div>
                        <h2>Inventory Synchronization</h2>
                        <p>Keep this site inventory aligned with your SIEM dashboard.</p>
                    </div>
                    <span class="vulnity-sync-pill <?php echo esc_attr($sync_status_css); ?>"><?php echo esc_html($sync_status_label); ?></span>
                </header>

                <div class="vulnity-sync-rows">
                    <div class="vulnity-sync-row">
                        <span class="sync-label">Status</span>
                        <span class="sync-value"><?php echo esc_html($sync_status_label); ?></span>
                    </div>
                    <div class="vulnity-sync-row">
                        <span class="sync-label">Last sync</span>
                        <span class="sync-value"><?php echo esc_html($settings_last_sync_text); ?></span>
                    </div>
                    <div class="vulnity-sync-row">
                        <span class="sync-label">Next scheduled sync</span>
                        <span class="sync-value"><?php echo esc_html($settings_next_sync_text); ?></span>
                    </div>
                    <div class="vulnity-sync-row">
                        <span class="sync-label">Automatic frequency</span>
                        <span class="sync-value">Every 24 hours</span>
                    </div>
                </div>

                <div class="vulnity-sync-action-bar">
                    <button type="button" class="button button-primary" id="sync-inventory-btn" onclick="vulnitySyncInventory()">Sync Now</button>
                    <span id="sync-result"></span>
                </div>

                <div class="vulnity-sync-subpanel">
                    <h3>Coverage Snapshot</h3>
                    <div class="vulnity-sync-mini-grid is-compact">
                        <div class="vulnity-sync-mini-item">
                            <span class="mini-label">Tracked assets</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($sync_tracked_assets_total)); ?></span>
                        </div>
                        <div class="vulnity-sync-mini-item">
                            <span class="mini-label">Pending updates</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($sync_pending_updates_total)); ?></span>
                        </div>
                        <div class="vulnity-sync-mini-item">
                            <span class="mini-label">Admins tracked</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_administrators)); ?></span>
                        </div>
                        <div class="vulnity-sync-mini-item">
                            <span class="mini-label">Transport</span>
                            <span class="mini-value">Secure SIEM API</span>
                        </div>
                    </div>
                </div>
            </section>

            <section class="card vulnity-sync-panel">
                <header class="vulnity-sync-header">
                    <div>
                        <h2>Synchronization Policy</h2>
                        <p>What is synchronized and how often.</p>
                    </div>
                    <span class="vulnity-sync-pill is-neutral">Managed</span>
                </header>

                <ul class="vulnity-sync-checklist">
                    <li>WordPress core version and update status</li>
                    <li>Plugins and themes with available updates</li>
                    <li>Server runtime information (PHP and environment)</li>
                    <li>User and administrator inventory</li>
                    <li>Security configuration metadata</li>
                    <li>Installed security tooling signals</li>
                </ul>

                <div class="vulnity-sync-policy-grid">
                    <div class="vulnity-sync-policy-item">
                        <span class="policy-label">Automatic sync</span>
                        <span class="policy-value">Every 24 hours</span>
                    </div>
                    <div class="vulnity-sync-policy-item">
                        <span class="policy-label">Manual sync</span>
                        <span class="policy-value">On demand</span>
                    </div>
                    <div class="vulnity-sync-policy-item">
                        <span class="policy-label">Delivery</span>
                        <span class="policy-value">SIEM API</span>
                    </div>
                </div>

                <div class="vulnity-sync-subpanel">
                    <h3>Recommended Workflow</h3>
                    <ul class="vulnity-sync-checklist">
                        <li>Run manual sync after plugin, theme, or core changes.</li>
                        <li>Review pending updates after each successful synchronization.</li>
                        <li>Verify status is synchronized at least once per day.</li>
                    </ul>
                </div>
            </section>

            <?php if (!empty($inventory_summary)): ?>
            <section class="card vulnity-sync-panel vulnity-sync-panel-wide vulnity-inventory-summary-card">
                <header class="vulnity-sync-header">
                    <div>
                        <h2>Current Inventory Snapshot</h2>
                        <p>Latest synchronized components and update posture.</p>
                    </div>
                    <span class="vulnity-sync-pill is-info">Live data</span>
                </header>

                <div class="vulnity-sync-mini-grid is-compact">
                    <div class="vulnity-sync-mini-item">
                        <span class="mini-label">Total plugins</span>
                        <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_plugins_total)); ?></span>
                    </div>
                    <div class="vulnity-sync-mini-item">
                        <span class="mini-label">Active plugins</span>
                        <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_plugins_active)); ?></span>
                    </div>
                    <div class="vulnity-sync-mini-item">
                        <span class="mini-label">Themes</span>
                        <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_themes_total)); ?></span>
                    </div>
                    <div class="vulnity-sync-mini-item">
                        <span class="mini-label">Users</span>
                        <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_users_total)); ?></span>
                    </div>
                </div>

                <table class="wp-list-table widefat vulnity-sync-table">
                    <thead>
                        <tr>
                            <th>Component</th>
                            <th>Version</th>
                            <th>Update Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><strong>WordPress Core</strong></td>
                            <td><?php echo esc_html($inventory_summary['wordpress_version'] ?? 'Unknown'); ?></td>
                            <td>
                                <?php $core_update_available = !empty($inventory_summary['wordpress_update']); ?>
                                <span class="vulnity-sync-badge <?php echo esc_attr($core_update_available ? 'is-warning' : 'is-success'); ?>">
                                    <?php echo esc_html($core_update_available ? 'Update available' : 'Up to date'); ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td><strong>PHP</strong></td>
                            <td><?php echo esc_html($inventory_summary['php_version'] ?? 'Unknown'); ?></td>
                            <td><span class="vulnity-sync-badge is-neutral">Informational</span></td>
                        </tr>
                        <tr>
                            <td><strong>Plugins</strong></td>
                            <td><?php echo esc_html(number_format_i18n($inventory_plugins_active)); ?> / <?php echo esc_html(number_format_i18n($inventory_plugins_total)); ?> active</td>
                            <td>
                                <?php $plugins_have_updates = !empty($inventory_summary['plugins_updates']); ?>
                                <span class="vulnity-sync-badge <?php echo esc_attr($plugins_have_updates ? 'is-warning' : 'is-success'); ?>">
                                    <?php
                                    echo esc_html(
                                        $plugins_have_updates
                                            ? number_format_i18n($inventory_plugins_updates) . ' updates available'
                                            : 'All up to date'
                                    );
                                    ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td><strong>Themes</strong></td>
                            <td><?php echo esc_html(number_format_i18n($inventory_themes_total)); ?> installed</td>
                            <td>
                                <?php $themes_have_updates = !empty($inventory_summary['themes_updates']); ?>
                                <span class="vulnity-sync-badge <?php echo esc_attr($themes_have_updates ? 'is-warning' : 'is-success'); ?>">
                                    <?php
                                    echo esc_html(
                                        $themes_have_updates
                                            ? number_format_i18n($inventory_themes_updates) . ' updates available'
                                            : 'All up to date'
                                    );
                                    ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td><strong>Administrators</strong></td>
                            <td><?php echo esc_html(number_format_i18n($inventory_administrators)); ?> users</td>
                            <td><span class="vulnity-sync-badge is-neutral">Inventory only</span></td>
                        </tr>
                    </tbody>
                </table>
            </section>
            <?php endif; ?>
        </div>
    </div>

    <div class="vulnity-tab-content<?php echo esc_attr($tab_classes['settings']); ?> vulnity-tab-grid" id="tab-settings"<?php echo esc_attr($tab_visibility['settings']); ?>>
        <div class="vulnity-settings-shell">
            <section class="card vulnity-settings-panel vulnity-settings-panel-main">
                <header class="vulnity-settings-header">
                    <div>
                        <h2 data-vulnity-i18n="settings.connection_title">Connection</h2>
                        <p data-vulnity-i18n="settings.connection_subtitle">SIEM connection details and quick actions.</p>
                    </div>
                    <span class="vulnity-settings-pill vulnity-settings-pill-online" data-vulnity-i18n="settings.connected_pill">Connected</span>
                </header>

                <div class="vulnity-settings-details">
                    <div class="vulnity-settings-row">
                        <span class="vulnity-settings-label" data-vulnity-i18n="settings.status_label">Status</span>
                        <span class="vulnity-settings-value">
                            <span class="vulnity-status-indicator vulnity-status-connected"></span>
                            <strong data-vulnity-i18n="settings.connected_to_siem">Connected to SIEM</strong>
                        </span>
                    </div>
                    <div class="vulnity-settings-row">
                        <span class="vulnity-settings-label" data-vulnity-i18n="settings.site_id_label">Site ID</span>
                        <code class="vulnity-settings-code"><?php echo esc_html($config['site_id']); ?></code>
                    </div>
                    <div class="vulnity-settings-row">
                        <span class="vulnity-settings-label" data-vulnity-i18n="settings.paired_since_label">Paired since</span>
                        <span class="vulnity-settings-value"><?php echo esc_html($config['paired_at']); ?></span>
                    </div>
                    <div class="vulnity-settings-row">
                        <span class="vulnity-settings-label" data-vulnity-i18n="settings.plugin_version_label">Plugin version</span>
                        <span class="vulnity-settings-value">v<?php echo esc_html(VULNITY_VERSION); ?></span>
                    </div>
                </div>

                <div class="vulnity-settings-language-card">
                    <div class="vulnity-settings-language-header">
                        <h3 data-vulnity-i18n="settings.language_title">Interface language</h3>
                        <span class="vulnity-settings-pill" id="vulnity-language-current">English</span>
                    </div>
                    <p data-vulnity-i18n="settings.language_desc">Visual only. This does not change backend behavior.</p>
                    <div class="vulnity-settings-language-switch" role="group" aria-label="Interface language">
                        <button type="button" class="button vulnity-language-option is-active" data-vulnity-lang="en" data-vulnity-i18n="settings.lang_en" aria-pressed="true">English</button>
                        <button type="button" class="button vulnity-language-option" data-vulnity-lang="es" data-vulnity-i18n="settings.lang_es" aria-pressed="false">Spanish</button>
                    </div>
                </div>

                <div class="vulnity-settings-actions">
                    <div class="vulnity-settings-action-card">
                        <h3 data-vulnity-i18n="settings.connection_test_title">Connection test</h3>
                        <p data-vulnity-i18n="settings.connection_test_desc">Verify SIEM connectivity.</p>
                        <div class="vulnity-settings-action-row">
                            <button type="button" class="button button-primary" onclick="vulnityTestConnection()" data-vulnity-i18n="settings.connection_test_button">Test Connection</button>
                            <span id="connection-test-result"></span>
                        </div>
                    </div>

                    <div class="vulnity-settings-action-card vulnity-settings-action-danger">
                        <h3 data-vulnity-i18n="settings.disconnect_title">Disconnect</h3>
                        <p data-vulnity-i18n="settings.disconnect_desc">This removes the site from SIEM monitoring.</p>
                        <div class="vulnity-settings-action-row">
                            <button type="button" class="button button-secondary" onclick="vulnityUnpair()" data-vulnity-i18n="settings.disconnect_button">Disconnect</button>
                        </div>
                    </div>
                </div>
            </section>

            <section class="card vulnity-settings-panel">
                <header class="vulnity-settings-header">
                    <div>
                        <h2 data-vulnity-i18n="settings.runtime_title">Security Runtime</h2>
                        <p data-vulnity-i18n="settings.runtime_subtitle">Active sensors and local processing behavior.</p>
                    </div>
                    <span class="vulnity-settings-pill" data-vulnity-i18n="settings.runtime_pill">8 sensors</span>
                </header>

                <ul class="vulnity-settings-sensor-list">
                    <li data-vulnity-i18n="settings.sensor_bruteforce">Brute Force Detection</li>
                    <li data-vulnity-i18n="settings.sensor_file_upload">File Upload Monitoring</li>
                    <li data-vulnity-i18n="settings.sensor_admin_changes">Admin Account Changes</li>
                    <li data-vulnity-i18n="settings.sensor_permissions">Permission Changes</li>
                    <li data-vulnity-i18n="settings.sensor_plugins_themes">Plugin and Theme Changes</li>
                    <li data-vulnity-i18n="settings.sensor_core_updates">Core Updates</li>
                    <li data-vulnity-i18n="settings.sensor_queries">Suspicious Queries</li>
                    <li data-vulnity-i18n="settings.sensor_xmlrpc">XML-RPC Attack Detection</li>
                </ul>

                <div class="vulnity-settings-metrics">
                    <div class="vulnity-settings-metric">
                        <span class="metric-label" data-vulnity-i18n="settings.metric_alert_retention_label">Alert retention</span>
                        <span class="metric-value" data-vulnity-i18n="settings.metric_alert_retention_value">Last 100 alerts</span>
                    </div>
                    <div class="vulnity-settings-metric">
                        <span class="metric-label" data-vulnity-i18n="settings.metric_sync_frequency_label">Sync frequency</span>
                        <span class="metric-value" data-vulnity-i18n="settings.metric_sync_frequency_value">Every hour</span>
                    </div>
                    <div class="vulnity-settings-metric">
                        <span class="metric-label" data-vulnity-i18n="settings.metric_retry_queue_label">Retry queue</span>
                        <span class="metric-value" data-vulnity-i18n="settings.metric_retry_queue_value">Every 5 minutes</span>
                    </div>
                </div>

                <div class="vulnity-settings-subpanel">
                    <h3 data-vulnity-i18n="settings.monitoring_scope_title">Monitoring Scope</h3>
                    <div class="vulnity-settings-mini-grid">
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.monitoring_active_plugins">Active plugins</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_plugins_active)); ?></span>
                        </div>
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.monitoring_themes">Themes</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_themes_total)); ?></span>
                        </div>
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.monitoring_users">Users</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_users_total)); ?></span>
                        </div>
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.monitoring_admins">Admins</span>
                            <span class="mini-value"><?php echo esc_html(number_format_i18n($inventory_administrators)); ?></span>
                        </div>
                    </div>
                </div>
            </section>

            <section class="card vulnity-settings-panel">
                <header class="vulnity-settings-header">
                    <div>
                        <h2 data-vulnity-i18n="settings.about_title">About Vulnity Security</h2>
                        <p data-vulnity-i18n="settings.about_subtitle">Version and support information.</p>
                    </div>
                    <span class="vulnity-settings-pill">v<?php echo esc_html(VULNITY_VERSION); ?></span>
                </header>
                <div class="vulnity-settings-about">
                    <p><strong data-vulnity-i18n="settings.about_version_label">Version:</strong> <?php echo esc_html(VULNITY_VERSION); ?></p>
                    <p data-vulnity-i18n="settings.about_line_1">Vulnity Security provides WordPress monitoring with SIEM integration for centralized visibility.</p>
                    <p data-vulnity-i18n="settings.about_line_2">Security events are detected locally and delivered to your SIEM dashboard.</p>
                    <p><strong data-vulnity-i18n="settings.about_support_label">Support:</strong> <span data-vulnity-i18n="settings.about_support_value">Use the Vulnity SIEM dashboard or contact support.</span></p>
                </div>

                <div class="vulnity-settings-subpanel">
                    <h3 data-vulnity-i18n="settings.snapshot_title">Synchronization Snapshot</h3>
                    <div class="vulnity-settings-mini-grid">
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.snapshot_status">Status</span>
                            <span class="mini-value"><?php echo esc_html($sync_status_label); ?></span>
                        </div>
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.snapshot_last_sync">Last sync</span>
                            <span class="mini-value"><?php echo esc_html($settings_last_sync_text); ?></span>
                        </div>
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.snapshot_next_sync">Next sync</span>
                            <span class="mini-value"><?php echo esc_html($settings_next_sync_text); ?></span>
                        </div>
                        <div class="vulnity-settings-mini-item">
                            <span class="mini-label" data-vulnity-i18n="settings.snapshot_support">Support</span>
                            <span class="mini-value" data-vulnity-i18n="settings.snapshot_support_value">SIEM dashboard / support team</span>
                        </div>
                    </div>
                </div>

                <div class="vulnity-settings-subpanel">
                    <h3 data-vulnity-i18n="settings.checklist_title">Operational Checklist</h3>
                    <ul class="vulnity-settings-checklist">
                        <li data-vulnity-i18n="settings.checklist_1">Run connection test after infrastructure changes.</li>
                        <li data-vulnity-i18n="settings.checklist_2">Review failed alerts in Alerts tab weekly.</li>
                        <li data-vulnity-i18n="settings.checklist_3">Keep plugin and WordPress core updated.</li>
                    </ul>
                </div>
            </section>
        </div>
    </div>

</div>
<?php
})();
