<?php
/**
 * VMPFence Dashboard View
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.0.0 Updated to reflect VMP WordPress Security branding and new dashboard layout.
 * @since 2.1.0 Added license refresh logic and status modal integration.
 * @since 2.1.2 -- Rule_id column issue fix and firewall detailed summary table fixed to have responsive layout
 * @since 2.2.2 Updated to reflect VMP Security branding, new license management
 * @since 2.2.4 SQL Query fix
 */

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

// Enqueue toast notification assets
wp_enqueue_style('vmpfence-toast-notifications', plugins_url('assets/css/toast-notifications.css', dirname(__FILE__)), array(), '1.0.3');
wp_enqueue_script('vmpfence-toast-notifications', plugins_url('assets/js/toast-notifications.js', dirname(__FILE__)), array('jquery'), '1.0.3', true);

// Refresh license status from API on EVERY dashboard load
// CRITICAL: This ensures server-side license changes (e.g., admin switching site from premium to free)
// are immediately reflected in the plugin UI without requiring plugin reactivation
$api_key = VMPFence_Config::get('central_api_key', '');
if (!empty($api_key)) {
    // ✅ REMOVED: Transient caching that prevented immediate license sync
    // OLD: Only refresh every 30 seconds - caused delays when admin changes license tier
    // NEW: Always refresh on dashboard load - ensures UI shows current server state
    
    require_once VMPFENCE_PLUGIN_DIR . 'lib/class-api-client.php';
    $api_client = new VMPFence_API_Client();
    $response = $api_client->check_api_key($api_key);
    
    if (!is_wp_error($response) && isset($response['is_valid']) && $response['is_valid']) {
        // Update license settings with fresh data from API
        // ✅ CRITICAL FIX: Store license_key for BOTH free and premium licenses
        $license_key_to_store = $response['license_key'] ?? '';
        $license_type = $response['license_type'] ?? 'free';
        
        // ✅ CRITICAL FIX: Always update local settings with server data
        // This ensures when admin changes license tier on server, plugin UI updates immediately
        VMPFence_License::update_license_settings(array(
            'license_type' => $license_type,
            'license_key' => $license_key_to_store,
            'expires_at' => $response['expires_at'] ?? null,
            'max_activations' => $response['max_activations'] ?? 1,
        ));
        
        // Also update vmpfence_license_status to ensure all checks see the same value
        update_option('vmpfence_license_status', array(
            'type' => $license_type,
            'key' => $license_key_to_store,
            'updated_at' => current_time('mysql')
        ));
    }
}

// Enqueue Toast Notification System (required for License Management and Global Options)
wp_enqueue_style('vmpfence-toast-notifications', VMPFENCE_PLUGIN_URL . 'admin/assets/css/toast-notifications.css', array(), VMPFENCE_VERSION);
wp_enqueue_script('vmpfence-toast-notifications', VMPFENCE_PLUGIN_URL . 'admin/assets/js/toast-notifications.js', array('jquery'), VMPFENCE_VERSION, true);

// Enqueue Premium Upgrade Button Handler (required for "UPGRADE TO PREMIUM" buttons)
wp_enqueue_script('vmpfence-premium-upgrade', VMPFENCE_PLUGIN_URL . 'admin/assets/js/premium-upgrade.js', array('jquery'), VMPFENCE_VERSION, true);

// Enqueue Chart.js library (needed for Total Attacks Blocked graph)
wp_enqueue_script('chartjs', 'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js', array(), '4.4.0', true);

// Enqueue firewall CSS
wp_enqueue_style('vmpfence-firewall', VMPFENCE_PLUGIN_URL . 'admin/assets/css/firewall.css', array(), VMPFENCE_VERSION);

// Enqueue firewall JS
wp_enqueue_script('vmpfence-firewall-js', VMPFENCE_PLUGIN_URL . 'admin/assets/js/firewall.js', array('jquery'), VMPFENCE_VERSION, true);
wp_localize_script('vmpfence-firewall-js', 'vmpfence_firewall', array(
    'nonce' => wp_create_nonce('vmpfence_firewall_nonce')
));

// Get current firewall status
$firewall_enabled = VMPFence_Config::get('waf_enabled');
$firewall_enabled_text = $firewall_enabled ? 'WAF Protection Enabled' : 'WAF Protection Disabled';

?>

<div class="wrap">
    <!-- WordPress Notices -->
    <?php settings_errors(); ?>
</div>

<!-- vmpfence Header Banner -->
<div class="vmpfence-header-banner">
    <div class="vmpfence-logo-section">
        <div class="vmpfence-logo">
            <img src="<?php echo esc_url( VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg' ); ?>" alt="VMP Security" style="width: 32px; height: 32px;"> 
            <span class="brand-header">VMP Security</span>
        </div>
    </div>
    <!-- <div class="vmpfence-header-right">
        <a href="#" class="vmpfence-learn-more">Learn more ↗</a>
    </div> -->
</div>

<!-- Protection Activated Banner -->
<div class="vmpfence-protection-banner">
    <span style="position: relative; z-index: 1;">VMP Security Protection Activated</span>
</div>

<!-- Main Dashboard Grid -->
<div class="vmpfence-main-grid">
        <!-- Row 1: Firewall Circle, Scan Circle, Premium Panel -->
        <div class="vmpfence-row vmpfence-row-1">
            <?php
            // Calculate firewall percentage using status calculator
            require_once VMPFENCE_PLUGIN_DIR . 'status-modal/controllers/class-status-calculator.php';
            $firewall_status_data = VMPFence_Status_Calculator::get_status_data('firewall_overall');
            $firewall_percentage = round($firewall_status_data['percentage'] * 100);
            
            // Set firewall color based on percentage
            if ($firewall_percentage >= 80) {
                $firewall_color = '#28a745'; // Green for excellent
            } elseif ($firewall_percentage >= 60) {
                $firewall_color = '#17a2b8'; // Blue for good  
            } elseif ($firewall_percentage >= 40) {
                $firewall_color = '#ffc107'; // Yellow for fair
            } else {
                $firewall_color = '#dc3545'; // Red for poor/disabled
            }
            ?>
            <div class="vmpfence-progress-item" id="vmpfence-firewall-progress">
                <div class="vmpfence-circle-progress" data-status-type="firewall_overall">
                    <svg class="vmpfence-circle-chart" viewbox="0 0 33.83098862 33.83098862" width="120" height="120">
                        <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <circle class="vmpfence-circle-progress-bar vmpfence-firewall-progress-bar" stroke="<?php echo esc_attr($firewall_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($firewall_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <text x="16.91549431" y="21.91549431" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" class="vmpfence-circle-text vmpfence-firewall-text"><?php echo esc_html($firewall_percentage); ?>%</text>
                    </svg>
                </div>
                <div class="vmpfence-progress-info">
                    <h3>Firewall</h3>
                    <p><?php echo $firewall_enabled_text; ?></p>
                    <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-firewall') ); ?>" class="vmpfence-manage-link">Manage Firewall</a>
                </div>
            </div>
            
            <?php
            // Calculate dynamic scan percentage using status calculator
            $scan_status_data = VMPFence_Status_Calculator::get_status_data('scan_overall');
            $scan_type = (string) VMPFence_Config::get('scanType');
            $scan_type = ucwords(str_replace('_', ' ', strtolower($scan_type)));
            $scan_percentage = round($scan_status_data['percentage'] * 100);
            $scan_color = '#1e73be'; // Default blue
            // Set color based on percentage
            if ($scan_percentage >= 80) {
                $scan_color = '#28a745'; // Green for excellent
            } elseif ($scan_percentage >= 60) {
                $scan_color = '#17a2b8'; // Blue for good  
            } elseif ($scan_percentage >= 40) {
                $scan_color = '#ffc107'; // Yellow for fair
            } else {
                $scan_color = '#dc3545'; // Red for poor
            }
            ?>
            <div class="vmpfence-progress-item" id="vmpfence-scan-progress">
                <div class="vmpfence-circle-progress" data-status-type="scan_overall">
                    <svg class="vmpfence-circle-chart" viewbox="0 0 33.83098862 33.83098862" width="120" height="120">
                        <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <circle class="vmpfence-circle-progress-bar vmpfence-scan-progress-bar" stroke="<?php echo esc_attr($scan_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($scan_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <text x="16.91549431" y="21.91549431" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" class="vmpfence-circle-text vmpfence-scan-text"><?php echo esc_html($scan_percentage); ?>%</text>
                    </svg>
                </div>
                <div class="vmpfence-progress-info">
                    <h3>Scan</h3>
                    <p class="vmpfence-scan-status-message"><?php echo esc_html($scan_status_data['missing'][0]['title'] ?? 'Excellent security coverage'); ?></p>
                    <small style="color: #666; font-style: italic; display: block; text-align: center;">Type: <?php echo esc_html($scan_type); ?></small>
                    <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-scan') ); ?>" class="vmpfence-manage-link">Manage Scan</a>
                </div>
            </div>
            
            <?php
            // Check premium status using the proper method
            $license_type = VMPFence_License::get_license_type();
            $is_premium = ($license_type === VMPFence_Constants::LICENSE_PREMIUM);
            ?>
            <div class="vmpfence-progress-item" id="vmpfence-premium-progress">
                <?php if (!$is_premium): ?>
                    <div class="vmpfence-premium-disabled">
                        <h3>Premium Protection Disabled</h3>
                        <p>As a free VMP Security user, you are currently using the Community version of the Threat Defense Feed. Premium users are protected by real-time malware signatures. Upgrade to Premium today to improve your protection.</p>
                        <div class="vmpfence-premium-buttons">
                            <a href="#" class="vmpfence-premium-upgrade-btn">UPGRADE TO PREMIUM</a>
                            <a href="#" target="_self" class="vmpfence-premium-learn-btn">LEARN MORE</a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="vmpfence-premium-enabled">
                        <h2>Premium Protection Enabled</h2>
                        <p>Your site is protected by real-time malware signatures</p>
                    </div>
                    <div class="vmpfence-premium-buttons">
                            <!-- <a href="#" class="vmpfence-premium-upgrade-btn">UPGRADE TO PREMIUM</a>
                            <a href="#" target="_self" class="vmpfence-premium-learn-btn">LEARN MORE</a> -->
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Row 2: Notifications and Central Status -->
        <div class="vmpfence-row vmpfence-row-2">
            <?php
            // Get dynamic notification data
            $notifications = [];
            $notification_count = 0;
            
            // Always get fresh count from database (not cached option)
            global $wpdb;
            $table_name = $wpdb->prefix . 'vmpfence_scan_issues';
            $recent_issues = (int) $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE STATUS != 'ignored'");  // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            
            if ($recent_issues > 0) {
                $notifications[] = [
                    'type' => 'security',
                    'icon' => '🚨',
                    'message' => $recent_issues . ' issues found in most recent scan',
                    'link' => admin_url('admin.php?page=vmpfence-scan'),
                    'dismissible' => true
                ];
                $notification_count++;
            }
            
            // Check for available updates from database (excluding ignored)
            global $wpdb;
            $table_name = $wpdb->prefix . 'vmpfence_scan_issues';
            
            // Count plugin updates (not ignored)
            $plugin_updates = (int) $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE issue_type = %s AND type = %s AND status != 'ignored'", 'file_changes', 'plugin_update'  // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            ));
            
            // Count theme updates (not ignored)
            $theme_updates = (int) $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE issue_type = %s AND type = %s AND status != 'ignored'", 'file_changes', 'theme_update'  // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            ));
            
            $total_updates = $plugin_updates + $theme_updates;
            if ($total_updates > 0) {
                $update_message = 'Updates are available for ';
                $parts = [];
                if ($plugin_updates > 0) {
                    $parts[] = $plugin_updates . ' plugin' . ($plugin_updates > 1 ? 's' : '');
                }
                if ($theme_updates > 0) {
                    $parts[] = $theme_updates . ' theme' . ($theme_updates > 1 ? 's' : '');
                }
                $update_message .= implode(' and ', $parts);
                
                $notifications[] = [
                    'type' => 'updates',
                    'icon' => '🔄',
                    'message' => $update_message,
                    'link' => admin_url('update-core.php'),
                    'dismissible' => true
                ];
                $notification_count++;
            }
            ?>
            
            <div class="vmpfence-section" id="vmpfence-notifications-section">
                <div class="vmpfence-section-header">
                    <h3>
                        <!-- <span style="font-size: 20px;">🔔</span>  -->
                        <span>Notifications</span>
                        <?php if ($notification_count > 0): ?>
                            <span class="vmpfence-notification-count"><?php echo esc_html($notification_count); ?></span>
                        <?php endif; ?>
                    </h3>
                </div>
                <div class="vmpfence-section-content">
                    <?php if (empty($notifications)): ?>
                        <div style="text-align: center; padding: 40px 20px;">
                            <div style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;">🔔</div>
                            <p style="color: #95a5a6; font-style: italic; margin: 0; font-size: 15px;">No notifications at this time</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($notifications as $notification): ?>
                            <div class="vmpfence-notification-item" data-type="<?php echo esc_attr($notification['type']); ?>">
                                <?php if ($notification['dismissible']): ?>
                                    <span class="vmpfence-close-btn" onclick="closeNotification(this)">×</span>
                                <?php endif; ?>
                                <span class="vmpfence-notification-icon-inline"><?php echo esc_html($notification['icon']); ?></span>
                                <?php if (isset($notification['link'])): ?>
                                    <a href="<?php echo esc_url($notification['link']); ?>" style="text-decoration: none; color: inherit;">
                                        <?php echo esc_html($notification['message']); ?>
                                    </a>
                                <?php else: ?>
                                    <?php echo esc_html($notification['message']); ?>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="vmpfence-central-status" style="cursor: not-allowed; opacity: 0.6;">
                <h3>VMP Security Central Status</h3>
                <div class="vmpfence-central-content">
                    <div class="vmpfence-central-icon">
                        <div class="vmpfence-connection-diagram">
                            <div class="vmpfence-center-node"></div>
                            <div class="vmpfence-outer-nodes">
                                <div class="vmpfence-node"></div>
                                <div class="vmpfence-node"></div>
                                <div class="vmpfence-node"></div>
                                <div class="vmpfence-node"></div>
                            </div>
                        </div>
                    </div>
                    <div class="vmpfence-central-info">
                        <p>VMP Security Central allows you to manage VMP Security on multiple sites from one location. It makes security monitoring and configuring VMP Security easier. <b style="color: #191970;">Central Website Coming Soon</b></p>
                        <p><strong>Connection:</strong> Not connected </p>
                        <p><strong>Audit Log:</strong> Disabled  <a href="#" style="pointer-events: none;">Manage</a></p>
                        <p><a href="#" style="pointer-events: none;">Connect This Site</a> &nbsp;&nbsp;&nbsp; <a href="#" style="pointer-events: none;">Visit VMP Security Central</a></p>
                    </div>
                </div>
            </div>

            <!-- <div class="vmpfence-section">
                <div class="vmpfence-section-header">
                    <h3>
                        <span style="font-size: 20px;">🔧</span> 
                        <span>Tools</span>
                    </h3>
                </div>
                <div class="vmpfence-section-content">
                    <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-tools') ); ?>" style="text-decoration: none;">
                        <div class="vmpfence-notification-item" style="display: flex; align-items: center; gap: 15px; padding: 18px 20px; background: linear-gradient(135deg, #f0f4ff 0%, #e8f0ff 100%); border-left: 4px solid #191970; border-radius: 8px; margin-bottom: 0; cursor: pointer;">
                            <span style="font-size: 2em;">🛠️</span>
                            <div style="flex: 1;">
                                <div style="font-weight: 700; color: #191970; font-size: 1.1em; margin-bottom: 4px;">
                                    Advanced Tools
                                </div>
                                <div style="color: #555; font-size: 0.95em; line-height: 1.4;">
                                    Live Traffic, Whois Lookup, Import/Export, and Diagnostics
                                </div>
                            </div>
                            <span style="color: #191970; font-size: 1.5em;">→</span>
                        </div>
                    </a>
                </div>
            </div> -->

        </div>
        
        <!-- Row 3: Tools, Help, Global Options -->
        <div class="vmpfence-row vmpfence-row-3">
            <div class="vmpfence-tools-quicklink">
                <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-tools') ); ?>" class="vmpfence-tool-item vmpfence-tool-link">
                    <div class="vmpfence-tool-icon">🔧</div>
                    <div class="vmpfence-tool-content">
                        <h4>Tools</h4>
                        <p>Live Traffic, Whois Lookup, Import/Export, and Diagnostics</p>
                    </div>
                </a>
            </div>
            
            <div class="vmpfence-help-quicklink">
                <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-help') ); ?>" class="vmpfence-tool-item vmpfence-tool-link">
                    <div class="vmpfence-tool-icon">❓</div>
                    <div class="vmpfence-tool-content">
                        <h4>Help</h4>
                        <p>Find the documentation and help you need.</p>
                    </div>
                </a>
            </div>
            
            <div class="vmpfence-options-quicklink" id="vmpfence-global-options-link">
                <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-all-options#vmpfence-global-options') ); ?>" class="vmpfence-tool-item vmpfence-tool-link">
                    <div class="vmpfence-tool-icon">⚙️</div>
                    <div class="vmpfence-tool-content">
                        <h4>Global Options</h4>
                        <p>Manage global options for VMP Fence such as alerts, premium status, and more</p>
                    </div>
                </a>
            </div>
        </div>
        
        <!-- Row 4: Attack Chart and Summary -->
        <div class="vmpfence-row vmpfence-row-4">
            <!-- Firewall Summary Table Card -->
            <div class="vmpfence-chart-item" style="background: #fff; padding: 25px; border: 1px solid #ddd;">
                <h3 style="margin: 0 0 20px 0; font-size: 16px; font-weight: 600; color: #333;">
                    Firewall Summary: 
                    <span style="font-weight: 400; color: #666;">Attacks Blocked for <?php echo esc_html($_SERVER['SERVER_NAME'] . parse_url(home_url(), PHP_URL_PATH)); ?></span>
                </h3>
                
                <?php
                // Get attack data for the summary table
                global $wpdb;
                $waf_table = $wpdb->prefix . 'vmpfence_waf_log';
                $blocked_ips_table = $wpdb->prefix . 'vmpfence_blocked_ips';
                
                
                // Today's attacks by type
                $today_complex = (int) $wpdb->get_var("SELECT COUNT(*) FROM $waf_table WHERE action LIKE 'block%' AND attackLogTime >= UNIX_TIMESTAMP(CURDATE()) AND actionDescription LIKE '%WAF block:%'");
                $today_brute = (int) $wpdb->get_var("SELECT COUNT(*) FROM $blocked_ips_table WHERE blocked_at >= UNIX_TIMESTAMP(CURDATE()) AND reason LIKE '%brute force%' AND source = 'local'");
                $today_blocklist = (int) $wpdb->get_var("SELECT COUNT(*) FROM $blocked_ips_table WHERE blocked_at >= UNIX_TIMESTAMP(CURDATE()) AND source = 'local'");
                $today_total = $today_complex + $today_brute + $today_blocklist;
                
                
                // Week's attacks by type
                $week_complex = (int) $wpdb->get_var("SELECT COUNT(*) FROM $waf_table WHERE action LIKE 'block%' AND attackLogTime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) AND actionDescription LIKE '%WAF block:%'");
                $week_brute = (int) $wpdb->get_var("SELECT COUNT(*) FROM $blocked_ips_table WHERE blocked_at >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) AND reason LIKE '%brute force%' AND source = 'local'");
                $week_blocklist = (int) $wpdb->get_var("SELECT COUNT(*) FROM $blocked_ips_table WHERE blocked_at >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) AND source = 'local'");
                $week_total = $week_complex + $week_brute + $week_blocklist;
                                
                // Month's attacks by type
                $month_complex = (int) $wpdb->get_var("SELECT COUNT(*) FROM $waf_table WHERE action LIKE 'block%' AND attackLogTime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) AND actionDescription LIKE '%WAF block:%'");
                $month_brute = (int) $wpdb->get_var("SELECT COUNT(*) FROM $blocked_ips_table WHERE blocked_at >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) AND reason LIKE '%brute force%' AND source = 'local'");
                $month_blocklist = (int) $wpdb->get_var("SELECT COUNT(*) FROM $blocked_ips_table WHERE blocked_at >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) AND source = 'local'");
                $month_total = $month_complex + $month_brute + $month_blocklist;
                                
                // Check if premium
                $is_premium = (VMPFence_License::get_license_type() === VMPFence_Constants::LICENSE_PREMIUM);
                ?>
                
                <table style="width: 100%; border-collapse: collapse; margin-top: 15px;">
                    <thead>
                        <tr style="border-bottom: 1px solid #e0e0e0;">
                            <th style="padding: 12px 15px; text-align: left; font-weight: 600; color: #333; font-size: 14px;">Block Type</th>
                            <th style="padding: 12px 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;">Complex</th>
                            <th style="padding: 12px 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;">Brute Force</th>
                            <th style="padding: 12px 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;">Blocklist</th>
                            <th style="padding: 12px 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;">Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr style="border-bottom: 1px solid #f0f0f0;">
                            <td style="padding: 15px; font-weight: 600; color: #333; font-size: 14px;">Today</td>
                            <td style="padding: 15px; text-align: center; color: #555; font-size: 14px;"><?php echo number_format($today_complex); ?></td>
                            <td style="padding: 15px; text-align: center; color: #555; font-size: 14px;"><?php echo number_format($today_brute); ?></td>
                            <td style="padding: 15px; text-align: center;">
                                <?php if ($is_premium): ?>
                                    <span style="color: #555; font-size: 14px;"><?php echo number_format($today_blocklist); ?></span>
                                <?php else: ?>
                                    <div style="color: #999; font-size: 14px; margin-bottom: 8px;">—</div>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;"><?php echo number_format($today_total); ?></td>
                        </tr>
                        <tr style="border-bottom: 1px solid #f0f0f0;">
                            <td style="padding: 15px; font-weight: 600; color: #333; font-size: 14px;">Week</td>
                            <td style="padding: 15px; text-align: center; color: #555; font-size: 14px;"><?php echo number_format($week_complex); ?></td>
                            <td style="padding: 15px; text-align: center; color: #555; font-size: 14px;"><?php echo number_format($week_brute); ?></td>
                            <td style="padding: 15px; text-align: center;">
                                <?php if ($is_premium): ?>
                                    <span style="color: #555; font-size: 14px;"><?php echo number_format($week_blocklist); ?></span>
                                <?php else: ?>
                                    <button style="background: #191970; color: white; border: none; padding: 8px 20px; border-radius: 4px; font-size: 13px; font-weight: 500; cursor: pointer;">Premium</button>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;"><?php echo number_format($week_total); ?></td>
                        </tr>
                        <tr>
                            <td style="padding: 15px; font-weight: 600; color: #333; font-size: 14px;">Month</td>
                            <td style="padding: 15px; text-align: center; color: #555; font-size: 14px;"><?php echo number_format($month_complex); ?></td>
                            <td style="padding: 15px; text-align: center; color: #555; font-size: 14px;"><?php echo number_format($month_brute); ?></td>
                            <td style="padding: 15px; text-align: center;">
                                <?php if ($is_premium): ?>
                                    <span style="color: #555; font-size: 14px;"><?php echo number_format($month_blocklist); ?></span>
                                <?php else: ?>
                                    <div style="color: #999; font-size: 14px; margin-bottom: 8px;">—</div>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 15px; text-align: center; font-weight: 600; color: #333; font-size: 14px;"><?php echo number_format($month_total); ?></td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- <div style="margin-top: 20px; text-align: right;">
                    <a href="#" style="color: #0073aa; text-decoration: none; font-size: 13px; display: inline-flex; align-items: center; gap: 5px;">
                        <span style="display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; border-radius: 50%; border: 2px solid #0073aa; font-size: 12px; font-weight: 600;">?</span>
                        How are these categorized?
                    </a>
                </div> -->
            </div>
            
            <!-- Attack Chart Card -->
            <div class="vmpfence-chart-item">
                <h3>Total Attacks Blocked: <span>VMP Security Network</span></h3>
                <div class="vmpfence-chart-controls">
                    <button class="vmpfence-chart-btn vmpfence-active" id="chart-24h">24 Hours</button>
                    <button class="vmpfence-chart-btn" id="chart-30d">30 Days</button>
                </div>
                <div class="vmpfence-chart-container" style="position: relative; height: 300px; margin-top: 20px;">
                    <canvas id="attacksChart"></canvas>
                </div>
                <div style="text-align: center; margin-top: 15px;">
                    <span id="vmpfence-chart-timestamp" style="color: #d68a00; font-style: italic; font-size: 13px;">Loading...</span>
                </div>
            </div>
        </div>

    <!-- Recent Blocked Attacks Table -->
    <div class="vmpfence-firewall-table-section">
        <?php
        
        // Get filter parameter
        $filter = isset($_GET['attack_filter']) ? sanitize_text_field($_GET['attack_filter']) : 'today';
        ?>
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="margin: 0;">Firewall Detailed Summary: Attacks Blocked for <?php echo esc_html($_SERVER['SERVER_NAME'] . parse_url(home_url(), PHP_URL_PATH)); ?></h3>
            <div class="attack-filter-controls">
                <button class="attack-filter-btn <?php echo ($filter === 'today') ? 'active' : ''; ?>" data-filter="today">Today</button>
                <button class="attack-filter-btn <?php echo ($filter === '7days') ? 'active' : ''; ?>" data-filter="7days">Last 7 Days</button>
                <button class="attack-filter-btn <?php echo ($filter === '30days') ? 'active' : ''; ?>" data-filter="30days">Last 30 Days</button>
                <button class="attack-filter-btn <?php echo ($filter === 'all') ? 'active' : ''; ?>" data-filter="all">All Time</button>
            </div>
        </div>
        
        <div id="firewall-summary-content">
        <?php
        // Get attack counts for stats
        global $wpdb;
        $table_name = $wpdb->prefix . 'vmpfence_waf_log';
        
        $stats_today = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE action LIKE 'block%' AND attackLogTime >= UNIX_TIMESTAMP(CURDATE())");
        $stats_7days = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE action LIKE 'block%' AND attackLogTime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))");
        $stats_30days = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE action LIKE 'block%' AND attackLogTime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))");
        $stats_all = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE action LIKE 'block%'");
        ?>
        <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px;">
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; text-align: center;">
                <div>
                    <div style="font-size: 28px; font-weight: 700; color: #191970; margin-bottom: 5px;"><?php echo number_format($stats_today); ?></div>
                    <div style="font-size: 13px; color: #666;">Blocked Today</div>
                </div>
                <div>
                    <div style="font-size: 28px; font-weight: 700; color: #191970; margin-bottom: 5px;"><?php echo number_format($stats_7days); ?></div>
                    <div style="font-size: 13px; color: #666;">Last 7 Days</div>
                </div>
                <div>
                    <div style="font-size: 28px; font-weight: 700; color: #191970; margin-bottom: 5px;"><?php echo number_format($stats_30days); ?></div>
                    <div style="font-size: 13px; color: #666;">Last 30 Days</div>
                </div>
                <div>
                    <div style="font-size: 28px; font-weight: 700; color: #191970; margin-bottom: 5px;"><?php echo number_format($stats_all); ?></div>
                    <div style="font-size: 13px; color: #666;">All Time</div>
                </div>
            </div>
        </div>
        
        <?php
        
        // Build time condition based on filter
        $time_condition = '';
        switch ($filter) {
            case 'today':
                $time_condition = 'AND attackLogTime >= UNIX_TIMESTAMP(CURDATE())';
                break;
            case '7days':
                $time_condition = 'AND attackLogTime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))';
                break;
            case '30days':
                $time_condition = 'AND attackLogTime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))';
                break;
            default:
                $time_condition = '';
        }
        
        // Get recent blocked attacks from WAF log
        global $wpdb;
        $table_name = $wpdb->prefix . 'vmpfence_waf_log';
        $recent_attacks = $wpdb->get_results(
            "SELECT 
                id,
                DATE_FORMAT(FROM_UNIXTIME(attackLogTime), '%Y-%m-%d %H:%i:%s') as created_at,
                INET6_NTOA(IP) as ip_address,
                actionDescription as attack_description,
                actionData,
                logMsg,
                action,
                severity
            FROM $table_name
            WHERE action LIKE 'block%' {$time_condition}
            GROUP BY id
            ORDER BY attackLogTime DESC
            LIMIT 50",
            ARRAY_A
        );
        
        // Parse violations from actionData
        foreach ($recent_attacks as &$attack) {
            $data = json_decode($attack['actionData'], true);
            if (!empty($data['violated_rules']) && is_array($data['violated_rules'])) {
                $first_violation = reset($data['violated_rules']);
                $attack['attack_type'] = isset($first_violation['category']) ? $first_violation['category'] : 'Unknown';
                $attack['rule_id'] = isset($first_violation['rule_id']) ? $first_violation['rule_id'] : 'N/A';
            } else {
                $attack['attack_type'] = 'Unknown';
                $attack['rule_id'] = 'N/A';
            }
        }
        unset($attack); // Break the reference to avoid bugs in the next foreach
        ?>
        <table class="wp-list-table widefat striped" style="table-layout: auto;">
            <thead>
                <tr>
                    <th style="width: 140px;">Date/Time</th>
                    <th style="width: 130px;">IP Address</th>
                    <th style="width: 120px;">Attack Type</th>
                    <!-- <th style="width: 10%;">Rule ID</th> -->
                    <th style="width: auto;">Description</th>
                    <th style="width: 90px;">Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($recent_attacks)): ?>
                    <?php foreach ($recent_attacks as $attack): ?>
                    <tr>
                        <td><?php echo esc_html($attack['created_at']); ?></td>
                        <td><?php echo esc_html($attack['ip_address'] ?: 'Unknown'); ?></td>
                        <td>
                            <span class="badge badge-<?php echo esc_attr(strtolower($attack['attack_type'])); ?>">
                                <?php echo esc_html($attack['attack_type']); ?>
                            </span>
                        </td>
                        <!-- <td><code><?php echo esc_html($attack['rule_id']); ?></code></td> -->
                        <td style="word-wrap: break-word; overflow-wrap: break-word; white-space: normal; max-width: 400px;"><?php echo esc_html($attack['logMsg']); ?></td>
                        <td><span class="vmpfence-status-blocked">Blocked</span></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 20px;">
                            <em><?php _e('No blocked attacks recorded yet. The firewall is active and monitoring your site.', 'vmpfence-security'); ?></em>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
        </div>
    </div>
    </div>
    
    <?php
    // License Management section removed - available in Global Options instead
    ?>
    
    <?php
    // Enqueue dashboard JavaScript
    wp_enqueue_script(
        'vmpfence-dashboard',
        plugin_dir_url(__FILE__) . '../assets/js/dashboard.js',
        array('jquery', 'vmpfence-toast-notifications'),
        VMPFENCE_VERSION,
        true
    );
    
    // Localize script data
    wp_localize_script(
        'vmpfence-dashboard',
        'vmpfence_dashboard_data',
        array(
            'last_scan_time' => esc_js( get_option("vmpfence_last_scan_data", [])["completed_time"] ?? current_time("mysql") )
        )
    );
    ?>


<!-- Inline Script: Notification Counter on Page Load (uses PHP data) -->
<script>
// Check for previously dismissed notifications on page load (inline version for PHP data)
document.addEventListener('DOMContentLoaded', function() {
    const dismissedNotifications = JSON.parse(localStorage.getItem('vmpfence_dismissed_notifications') || '{}');
    const currentScanTime = '<?php echo esc_js( get_option("vmpfence_last_scan_data", [])["completed_time"] ?? current_time("mysql") ); ?>';
    
    // Check each notification type to see if it should be hidden
    Object.keys(dismissedNotifications).forEach(function(type) {
        const dismissedData = dismissedNotifications[type];
        const notification = document.querySelector('.vmpfence-notification-item[data-type="' + type + '"]');
        
        if (notification && dismissedData.scanTime === currentScanTime) {
            // Only hide if dismissed for the current scan
            notification.style.display = 'none';
        }
    });
    
    // Clean up old dismissed notifications for scans that no longer exist
    const updatedDismissed = {};
    Object.keys(dismissedNotifications).forEach(function(type) {
        if (dismissedNotifications[type].scanTime === currentScanTime) {
            updatedDismissed[type] = dismissedNotifications[type];
        }
    });
    localStorage.setItem('vmpfence_dismissed_notifications', JSON.stringify(updatedDismissed));
    
    // Update counter after hiding dismissed notifications
    const sectionContent = document.querySelector('.vmpfence-section-content');
    if (sectionContent) {
        const visibleNotifications = sectionContent.querySelectorAll('.vmpfence-notification-item:not([style*="display: none"])');
        const counterElement = document.querySelector('.vmpfence-notification-count');
        const menuCountElement = document.querySelector('#adminmenu .vmpfence-menu-count');
        
        if (counterElement) {
            const visibleCount = visibleNotifications.length;
            
            // Store the count in localStorage
            localStorage.setItem('vmpfence_notification_count', visibleCount.toString());
            
            if (visibleCount === 0) {
                counterElement.style.display = 'none';
                
                // Also hide menu count
                if (menuCountElement) {
                    menuCountElement.style.display = 'none';
                }
                sectionContent.innerHTML = '<div style="text-align: center; padding: 40px 20px;"><div style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;">🔔</div><p style="color: #95a5a6; font-style: italic; margin: 0; font-size: 15px;">No notifications at this time</p></div>';
            } else {
                counterElement.textContent = visibleCount;
                
                // Update menu count to match
                if (menuCountElement) {
                    menuCountElement.textContent = visibleCount;
                }
            }
        }
    }
});
</script>


