<?php
/**
 * Dashboard Widget for VMP Security
 *
 * @package VMPFence
 * @since 2.2.2
 */

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

class VMPFence_Dashboard_Widget {
    
    /**
     * Initialize the dashboard widget
     */
    public static function init() {
        // Check if widget is enabled
        $widget_enabled = VMPFence_Config::get('enable_activity_widget', 1);
        
        if ($widget_enabled) {
            add_action('wp_dashboard_setup', array(__CLASS__, 'register_widget'));
            add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_widget_styles'));
        }
    }
    
    /**
     * Register the dashboard widget
     */
    public static function register_widget() {
        wp_add_dashboard_widget(
            'vmpfence_activity_widget',
            'VMP Security activity in the past week',
            array(__CLASS__, 'render_widget')
        );
    }
    
    /**
     * Enqueue widget styles
     */
    public static function enqueue_widget_styles($hook) {
        if ($hook !== 'index.php') {
            return;
        }
        
        wp_enqueue_style(
            'vmpfence-dashboard-widget',
            VMPFENCE_PLUGIN_URL . 'admin/assets/css/dashboard-widget.css',
            array(),
            VMPFENCE_VERSION
        );
        
        wp_enqueue_script(
            'vmpfence-dashboard-widget',
            VMPFENCE_PLUGIN_URL . 'admin/assets/js/dashboard-widget.js',
            array('jquery'),
            VMPFENCE_VERSION,
            true
        );
    }
    
    /**
     * Render the dashboard widget content
     */
    public static function render_widget() {
        ?>
        <div class="vmpfence-dashboard-widget">
            <!-- VMP Security Branding Header -->
            <div class="vmpfence-widget-branding">
                <img src="<?php echo esc_url(VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg'); ?>" alt="VMP Security" class="vmpfence-logo" width="50" height="50" />
                <div class="vmpfence-tagline">
                    <span class="vmpfence-brand-name">VMP Security</span>
                    <span class="vmpfence-brand-subtitle">Securing your <span class="vmpfence-wp-highlight">WordPress</span> website</span>
                </div>
            </div>
            
            <!-- Top 5 Blocked IPs -->
            <div class="vmpfence-widget-section">
                <h3 class="vmpfence-widget-title">Top 5 IPs Blocked</h3>
                <div class="vmpfence-widget-table">
                    <?php echo self::render_top_blocked_ips(); ?>
                </div>
                <div class="vmpfence-widget-actions">
                    <a href="<?php echo admin_url('admin.php?page=vmpfence-firewall&tab=blocking&view=ip'); ?>" class="button">Update Blocked IPs</a>
                </div>
            </div>
            
            <!-- Top 5 Countries Blocked -->
            <div class="vmpfence-widget-section">
                <h3 class="vmpfence-widget-title">Top 5 Countries Blocked</h3>
                <div class="vmpfence-widget-table">
                    <?php echo self::render_top_blocked_countries(); ?>
                </div>
                <div class="vmpfence-widget-actions">
                    <a href="<?php echo admin_url('admin.php?page=vmpfence-firewall&tab=blocking&view=country'); ?>" class="button">Update Blocked Countries</a>
                </div>
            </div>
            
            <!-- Top 5 Failed Logins -->
            <div class="vmpfence-widget-section">
                <h3 class="vmpfence-widget-title">Top 5 Failed Logins</h3>
                <div class="vmpfence-widget-table">
                    <?php echo self::render_top_failed_logins(); ?>
                </div>
                <div class="vmpfence-widget-actions">
                    <a href="<?php echo admin_url('admin.php?page=vmpfence-firewall&view=options#brute-force'); ?>" class="button">Update Login Security Options</a>
                </div>
            </div>
            
            <!-- Updates Needed -->
            <div class="vmpfence-widget-section">
                <h3 class="vmpfence-widget-title">Updates Needed</h3>
                <div class="vmpfence-updates-section">
                    <?php echo self::render_updates_needed(); ?>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render activity summary for the past week
     */
    private static function render_activity_summary() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'vmpfence_firewall_log';
        $seven_days_ago = date('Y-m-d H:i:s', strtotime('-7 days'));
        
        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            return '<p>No activity data available yet.</p>';
        }
        
        // Get blocked requests count
        $blocked_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE created_at >= %s AND action = 'blocked'",
            $seven_days_ago
        ));
        
        // Get unique IPs blocked
        $blocked_ips = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT ip_address) FROM $table_name WHERE created_at >= %s AND action = 'blocked'",
            $seven_days_ago
        ));
        
        $output = '<div class="vmpfence-stat-grid">';
        $output .= '<div class="vmpfence-stat-item">';
        $output .= '<div class="vmpfence-stat-value">' . number_format($blocked_count) . '</div>';
        $output .= '<div class="vmpfence-stat-label">Blocked Requests</div>';
        $output .= '</div>';
        $output .= '<div class="vmpfence-stat-item">';
        $output .= '<div class="vmpfence-stat-value">' . number_format($blocked_ips) . '</div>';
        $output .= '<div class="vmpfence-stat-label">Unique IPs Blocked</div>';
        $output .= '</div>';
        $output .= '</div>';
        
        return $output;
    }
    
    /**
     * Render top 5 blocked IPs
     */
    private static function render_top_blocked_ips() {
        global $wpdb;
        
        $blocked_ips_table = $wpdb->prefix . 'vmpfence_blocked_ips';
        
        $output = '<table class="vmpfence-widget-data-table">';
        $output .= '<thead><tr><th>IP</th><th>Country</th><th>Block Count</th></tr></thead>';
        $output .= '<tbody>';
        
        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$blocked_ips_table'") != $blocked_ips_table) {
            $output .= '<tr><td colspan="3">No IPs blocked yet.</td></tr>';
            $output .= '</tbody></table>';
            return $output;
        }
        
        // Get top 5 blocked IPs from the last 7 days
        $seven_days_ago = time() - (7 * 24 * 60 * 60);
        
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                ip_address,
                COUNT(*) as block_count
            FROM {$blocked_ips_table}
            WHERE source = 'local'
                AND blocked_at >= %d
            GROUP BY ip_address
            ORDER BY block_count DESC
            LIMIT 5",
            $seven_days_ago
        ));
        
        if (empty($results)) {
            $output .= '<tr><td colspan="3">No IPs blocked yet.</td></tr>';
        } else {
            foreach ($results as $row) {
                $country = self::get_country_for_ip($row->ip_address);
                $output .= '<tr>';
                $output .= '<td>' . esc_html($row->ip_address) . '</td>';
                $output .= '<td>' . esc_html($country) . '</td>';
                $output .= '<td>' . number_format($row->block_count) . '</td>';
                $output .= '</tr>';
            }
        }
        
        $output .= '</tbody></table>';
        
        return $output;
    }
    
    /**
     * Render top 5 blocked countries
     */
    private static function render_top_blocked_countries() {
        $output = '<table class="vmpfence-widget-data-table">';
        $output .= '<thead><tr><th>Country</th><th>Block Count</th></tr></thead>';
        $output .= '<tbody>';
        
        // Check if Blocked Country class exists
        if (!class_exists('VMPFence_Blocked_Country')) {
            $output .= '<tr><td colspan="2">No countries blocked yet.</td></tr>';
            $output .= '</tbody></table>';
            return $output;
        }
        
        // Get top 5 attacking countries from the last 7 days
        $results = VMPFence_Blocked_Country::get_top_attacking_countries('7d', 5);
        
        if (empty($results)) {
            $output .= '<tr><td colspan="2">No countries blocked yet.</td></tr>';
        } else {
            foreach ($results as $row) {
                $country_name = !empty($row['country_name']) ? $row['country_name'] : $row['country_code'];
                $output .= '<tr>';
                $output .= '<td>' . esc_html($country_name) . '</td>';
                $output .= '<td>' . number_format($row['attack_count']) . '</td>';
                $output .= '</tr>';
            }
        }
        
        $output .= '</tbody></table>';
        
        return $output;
    }
    
    /**
     * Render top 5 failed logins
     */
    private static function render_top_failed_logins() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'vmpfence_security_attempts';
        
        $output = '<table class="vmpfence-widget-data-table">';
        $output .= '<thead><tr><th>Username</th><th>Login Attempts</th><th>Existing User</th></tr></thead>';
        $output .= '<tbody>';
        
        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            $output .= '<tr><td colspan="3">No failed logins yet.</td></tr>';
            $output .= '</tbody></table>';
            return $output;
        }
        
        // Get time interval for past week (matching Wordfence approach)
        $interval = $wpdb->get_var("SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))");
        
        // Get top 5 usernames by failed login attempts in the past week
        // Group by username and count total failed attempts
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                a.username,
                COUNT(*) AS attempt_count,
                (
                    SELECT COUNT(*)
                    FROM {$wpdb->users} u
                    WHERE u.user_login COLLATE utf8mb4_unicode_ci = a.username COLLATE utf8mb4_unicode_ci
                       OR u.user_email COLLATE utf8mb4_unicode_ci = a.username COLLATE utf8mb4_unicode_ci
                ) AS user_exists
            FROM {$table_name} a
            WHERE a.event_type IN ('failed_login', 'invalid_username', 'blocked_username')
              AND UNIX_TIMESTAMP(a.attempt_time) > %d
            GROUP BY a.username
            ORDER BY attempt_count DESC
            LIMIT 5",
            $interval
        ));
        
        if (empty($results)) {
            $output .= '<tr><td colspan="3">No failed logins yet.</td></tr>';
        } else {
            foreach ($results as $row) {
                $output .= '<tr>';
                $output .= '<td>' . esc_html($row->username) . '</td>';
                $output .= '<td>' . number_format($row->attempt_count) . '</td>';
                $output .= '<td>' . ($row->user_exists > 0 ? 'Yes' : 'No') . '</td>';
                $output .= '</tr>';
            }
        }
        
        $output .= '</tbody></table>';
        
        return $output;
    }
    
    /**
     * Render updates needed section
     */
    private static function render_updates_needed() {
        $core_updates = get_core_updates();
        $plugin_updates = get_plugin_updates();
        $theme_updates = get_theme_updates();
        
        $output = '';
        
        // Core updates
        $output .= '<div class="vmpfence-update-category">';
        $output .= '<h4>Core</h4>';
        if (!empty($core_updates) && isset($core_updates[0]) && $core_updates[0]->response === 'upgrade') {
            $update = $core_updates[0];
            $output .= '<p>A new version of WordPress (' . esc_html($update->current) . ') is available.</p>';
            $output .= '<a href="' . admin_url('update-core.php') . '" class="button button-primary" style="background-color: #191970; border-color: #191970; color: white;">Update Now</a>';
        } else {
            $output .= '<p>WordPress is up to date.</p>';
        }
        $output .= '</div>';
        
        // Plugin updates
        $output .= '<div class="vmpfence-update-category">';
        $output .= '<h4>Plugins</h4>';
        if (!empty($plugin_updates)) {
            $count = count($plugin_updates);
            $output .= '<p>' . sprintf(_n('%s plugin update available.', '%s plugin updates available.', $count), number_format($count)) . '</p>';
            
            $output .= '<ul class="vmpfence-update-list">';
            $shown = 0;
            foreach ($plugin_updates as $plugin_file => $plugin_data) {
                if ($shown >= 5) break;
                $plugin_name = isset($plugin_data->Name) ? $plugin_data->Name : $plugin_file;
                $new_version = isset($plugin_data->update->new_version) ? $plugin_data->update->new_version : '';
                $output .= '<li>A new version of the plugin "' . esc_html($plugin_name) . '" (' . esc_html($new_version) . ') is available.</li>';
                $shown++;
            }
            $output .= '</ul>';
            $output .= '<a href="' . admin_url('update-core.php#update-plugins-table') . '" class="button" style="background-color: #191970; border-color: #191970; color: white;">Update Now</a>';
        } else {
            $output .= '<p>All plugins are up to date.</p>';
        }
        $output .= '</div>';
        
        // Theme updates
        $output .= '<div class="vmpfence-update-category">';
        $output .= '<h4>Themes</h4>';
        if (!empty($theme_updates)) {
            $count = count($theme_updates);
            $output .= '<p>' . sprintf(_n('%s theme update available.', '%s theme updates available.', $count), number_format($count)) . '</p>';
            
            $output .= '<ul class="vmpfence-update-list">';
            $shown = 0;
            foreach ($theme_updates as $theme_slug => $theme_data) {
                if ($shown >= 5) break;
                $theme_name = isset($theme_data->Name) ? $theme_data->Name : $theme_slug;
                $new_version = isset($theme_data->update['new_version']) ? $theme_data->update['new_version'] : '';
                $output .= '<li>A new version of the theme "' . esc_html($theme_name) . '" (' . esc_html($new_version) . ') is available.</li>';
                $shown++;
            }
            $output .= '</ul>';
            $output .= '<a href="' . admin_url('update-core.php#update-themes-table') . '" class="button" style="background-color: #191970; border-color: #191970; color: white;">Update Now</a>';
        } else {
            $output .= '<p>All themes are up to date.</p>';
        }
        $output .= '</div>';
        
        return $output;
    }
    
    /**
     * Get country name for IP address
     */
    private static function get_country_for_ip($ip) {
        // Try to use GeoIP lookup class if available
        if (class_exists('VMPFence_GeoIP_Lookup')) {
            $geoip = new VMPFence_GeoIP_Lookup();
            $result = $geoip->lookup($ip);
            if ($result && isset($result['country_name'])) {
                return $result['country_name'];
            }
        }
        
        return 'Unknown';
    }
}

// Initialize the dashboard widget
VMPFence_Dashboard_Widget::init();
