<?php
/**
 * VMPFence Dashboard Administration
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.0.0 Plugin Name changed to VMP WordPress Security
 * @since 2.2.0 Blocking page
 * @since 2.2.2 Plugin Name changed to VMP Security, All Options page add menu conditional display, Audit Log menu conditional display, Live Traffic menu conditional display, Blocking menu conditional display, AJAX handler for dashboard stats, setup redirection added to each page, setup overlay added
 * @since 2.2.4 Fixed logic - show overlay after modal is dismissed or on non-plugin pages, localize script added i18n strings
 */

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

/**
 * VMPFence Dashboard class
 */
class VMPFence_Dashboard {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_vmpfence_get_dashboard_stats', array($this, 'ajax_get_dashboard_stats'));
    }
    
    /**
     * Add admin menu
     * @since 1.0.0
     * @since 2.2.2 Always show menu, but individual pages will redirect to setup if needed
     */
    public function add_admin_menu() {
        // Always show menu, but individual pages will redirect to setup if needed
        $needs_setup = get_option('vmpfence_needs_setup', false);
        
        add_menu_page(
            'VMPFence Security',
            'VMP Security',
            'manage_options',
            'vmpfence-dashboard',
            array($this, 'dashboard_page'),
            VMPFENCE_PLUGIN_URL . 'admin/assets/images/vmp_default_logo.svg',
            30
        );

        // Add CSS to swap to white logo when menu is active/selected
        add_action('admin_enqueue_scripts', function() {
            $white_logo_url = plugin_dir_url(__FILE__) . 'assets/images/vmp_white_logo.svg';
            echo '<style>
                #adminmenu .toplevel_page_vmpfence-dashboard.current .wp-menu-image img,
                #adminmenu .toplevel_page_vmpfence-dashboard.wp-has-current-submenu .wp-menu-image img {
                    content: url(' . esc_url($white_logo_url) . ') !important;
                }
            </style>';
        });

        // Enqueue admin styles (includes menu icon styles)
        add_action('admin_enqueue_scripts', function() {
            wp_enqueue_style(
                'vmpfence-admin',
                plugin_dir_url(__FILE__) . 'assets/css/admin.css',
                array(),
                VMPFENCE_VERSION
            );
            
            // Enqueue script to update menu count from localStorage
            wp_add_inline_script('jquery', "
                jQuery(document).ready(function($) {
                    function updateMenuCountFromStorage() {
                        var notificationCount = localStorage.getItem('vmpfence_notification_count');
                        var menuItem = $('#adminmenu .wp-submenu a[href=\"admin.php?page=vmpfence-dashboard\"]');
                        
                        if (menuItem.length) {
                            // Remove existing count badge if any
                            menuItem.find('.vmpfence-menu-count').remove();
                            
                            // Add count badge if count > 0
                            if (notificationCount && parseInt(notificationCount) > 0) {
                                var badge = $('<span class=\"vmpfence-menu-count\">' + notificationCount + '</span>');
                                menuItem.append(badge);
                            }
                        }
                    }
                    
                    // Update on page load
                    updateMenuCountFromStorage();
                    
                    // Update when localStorage changes (for same-tab updates)
                    $(window).on('storage', updateMenuCountFromStorage);
                });
            ");
        });
        
        add_submenu_page(
            'vmpfence-dashboard',
            'Dashboard',
            'Dashboard',
            'manage_options',
            'vmpfence-dashboard',
            array($this, 'dashboard_page')
        );
        
        // Show Setup submenu during setup phase
        if ($needs_setup) {
            add_submenu_page(
                'vmpfence-dashboard',
                'Setup Wizard',
                '<span>Install</span>',
                'manage_options',
                'vmpfence-help&forced=1',
                array($this, 'help_page')
            );
        }
        
        add_submenu_page(
            'vmpfence-dashboard',
            'Firewall',
            'Firewall',
            'manage_options',
            'vmpfence-firewall',
            array($this, 'firewall_page')
        );
        
        // Blocked IPs removed from menu - now accessible via Firewall > Blocking tab
        // Redirect handler for backward compatibility
        add_submenu_page(
            null, // Hidden from menu
            'Blocked IPs',
            'Blocked IPs',
            'manage_options',
            'vmpfence-blocked-ips',
            array($this, 'blocked_ips_redirect')
        );
        
        add_submenu_page(
            'vmpfence-dashboard',
            'Scan',
            'Scan',
            'manage_options',
            'vmpfence-scan',
            array($this, 'scan_page')
        );
        
        add_submenu_page(
            'vmpfence-dashboard',
            'Tools',
            'Tools',
            'manage_options',
            'vmpfence-tools',
            array($this, 'tools_page')
        );
        
        // Conditional Blocking menu (shows Blocking tab page)
        if (VMPFence_Config::get('blocking_menu_display', 1) == 1) {
            add_submenu_page(
                'vmpfence-dashboard',
                'Blocking',
                'Blocking',
                'manage_options',
                'vmpfence-firewall&tab=blocking',
                array($this, 'firewall_page')
            );
        }
        
        // Conditional Live Traffic top-level menu item
        if (VMPFence_Config::get('display_live_traffic_menu', 0) == 1) {
            add_submenu_page(
                'vmpfence-dashboard',
                'Live Traffic',
                'Live Traffic',
                'manage_options',
                'vmpfence-live-traffic',
                array($this, 'tools_page')
            );
        }
        // Logging & Analytics - REMOVED: Now integrated as tab in Audit Log
        // add_submenu_page(
        //     'vmpfence-dashboard',
        //     '📊 Logging & Analytics',
        //     '📊 Logging & Analytics',
        //     'manage_options',
        //     'vmpfence-logging-analytics',
        //     array($this, 'logging_analytics_page')
        // );
        
        // CVE Scanner (Premium feature - requires API) - HIDDEN: Menu item removed
        // if (VMPFence_Config::is_api_available() && file_exists(VMPFENCE_PLUGIN_DIR . 'admin/pages/cve-scanner.php')) {
        //     add_submenu_page(
        //         'vmpfence-dashboard',
        //         'CVE Scanner',
        //         'CVE Scanner',
        //         'manage_options',
        //         'vmpfence-cve-scanner',
        //         array($this, 'cve_scanner_page')
        //     );
        // }

        // YARA Deep Scan (Premium feature - requires API) - HIDDEN: Menu item removed
        // if (VMPFence_Config::is_api_available() && file_exists(VMPFENCE_PLUGIN_DIR . 'admin/pages/yara-scanner.php')) {
        //     add_submenu_page(
        //         'vmpfence-dashboard',
        //         'YARA Deep Scan',
        //         'YARA Deep Scan',
        //         'manage_options',
        //         'vmpfence-yara-scanner',
        //         array($this, 'yara_scanner_page')
        //     );
        // }

        // Login Security / 2FA
        add_submenu_page(
            'vmpfence-dashboard',
            'Login Security',
            'Login Security',
            'manage_options',
            'vmpfence-login-security',
            array($this, 'login_security_page')
        );

        // Audit Log - conditional display
        if (VMPFence_Config::get('display_audit_log_menu', 1) == 1) {
            add_submenu_page(
                'vmpfence-dashboard',
                'Audit Log',
                'Audit Log',
                'manage_options',
                'vmpfence-audit-log',
                array($this, 'audit_log_page')
            );
        }

        // All Options - conditional menu display (page always accessible)
        if (VMPFence_Config::get('display_all_options_menu', 1) == 1) {
            add_submenu_page(
                'vmpfence-dashboard',
                'All Options',
                'All Options',
                'manage_options',
                'vmpfence-all-options',
                array($this, 'all_options_page')
            );
        } else {
            // Register page but hide from menu
            add_submenu_page(
                null,
                'All Options',
                'All Options',
                'manage_options',
                'vmpfence-all-options',
                array($this, 'all_options_page')
            );
        }

        /* Commented out for future releases */
        
        // add_submenu_page(
        //     'vmpfence-dashboard',
        //     'Login Security',
        //     'Login Security',
        //     'manage_options',
        //     'vmpfence-login-security',
        //     array($this, 'login_security_page')
        // );
        
        // add_submenu_page(
        //     'vmpfence-dashboard',
        //     'All Options',
        //     'All Options',
        //     'manage_options',
        //     'vmpfence-all-options',
        //     array($this, 'all_options_page')
        // );
        
        add_submenu_page(
            'vmpfence-dashboard',
            'Help',
            'Help',
            'manage_options',
            'vmpfence-help',
            array($this, 'help_page')
        );
        
        // Hidden page - Scan Options (not in submenu)
        add_submenu_page(
            null, // Hide from submenu
            'Scan Options and Scheduling',
            'Scan Options and Scheduling',
            'manage_options',
            'vmpfence-scan-options',
            array($this, 'scan_options_page')
        );
        
    }
    
    /**
     * 
     * Check if setup is incomplete and show overlay if needed
     * @since 2.2.2
     */
    private function check_setup_and_redirect() {
        if (get_option('vmpfence_needs_setup', false)) {
            // Add overlay to admin footer - page loads normally, overlay shows on top
            add_action('admin_footer', array($this, 'render_setup_overlay'));
        }
    }
    
    /**
     * Render setup required overlay on pages
     * @since 2.2.2
     * @since 2.2.3 Don't show overlay if activation modal will be displayed
     * @since 2.2.4 Fixed logic - show overlay after modal is dismissed or on non-plugin pages
     */
    public function render_setup_overlay() {
        // Don't show resume overlay if activation modal will be displayed
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
        $is_forced = isset($_GET['forced']) && $_GET['forced'] === '1';
        $show_activation_modal = get_transient('vmpfence_show_activation_modal');
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
        $is_help_page = isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'vmpfence-help';
        
        // Don't show overlay if:
        // 1. We're in forced mode (help page will show the modal)
        // 2. The activation modal transient is still active (modal is on plugins page)
        // 3. We're on the help page (activation modal handles this page)
        if ($is_forced || $show_activation_modal || $is_help_page) {
            return;
        }
        
        $setup_url = admin_url('admin.php?page=vmpfence-help&forced=1');
        ?>
        <style>
        .vmpfence-setup-required-overlay {
            position: fixed;
            top: 32px;
            left: 160px;
            right: 0;
            bottom: 0;
            background: rgba(241, 241, 241, 0.6);
            z-index: 999999;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .vmpfence-setup-required-overlay .vmpfence-overlay-notice {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            display: flex;
            align-items: center;
            padding: 0.5rem 1rem;
            background-color: #fcb214;
            z-index: 1;
            margin: 0 1.25rem;
        }
        .vmpfence-setup-required-overlay .vmpfence-overlay-notice .resume-btn {
            background-color: #fff;
            border-color: #191970;
            color: #191970;
            font-size: 16px;
            white-space: nowrap;
        }
        .vmpfence-setup-required-overlay .vmpfence-overlay-notice .resume-btn:hover {
            background-color: #bbbbbb;
        }
        @media screen and (max-width: 782px) {
            .vmpfence-setup-required-overlay {
                top: 46px;
                left: 0;
            }
        }
        .folded .vmpfence-setup-required-overlay {
            left: 36px;
        }
        </style>
        <div class="vmpfence-setup-required-overlay">
            <div class="vmpfence-overlay-notice">
                <div style="flex: 1;">
                    <strong style="font-size: 14px; font-weight: 400; font-family: 'Roboto', 'sans-serif'"><?php esc_html_e('VMP Security installation is incomplete', 'vmpfence-security'); ?></strong>
                </div>
                <a href="<?php echo esc_url($setup_url); ?>" class="button button-primary resume-btn">
                    <?php esc_html_e('RESUME INSTALLATION', 'vmpfence-security'); ?>
                </a>
            </div>
            <div style="max-width: 550px; text-align: center; padding: 20px; background: #191970; margin-left: -160px;">
                <h2 style="width: 510px; margin: 0 0 1rem -1.25rem; font-size: 16px; font-weight: 400; line-height: 1.5; font-family: 'Segoe UI', 'sans-serif'; color: #fff;">You must install a license to continue using VMP Security</h2>
                <a href="<?php echo esc_url($setup_url); ?>" 
                   class="button button-primary" 
                   style="background: #fff !important; border-radius:4px; color:#191970; border-color: #191970 !important; font-size: 14px; font-weight: 400; line-height: 1.3125; text-decoration: none; padding: 0.5rem 1.25rem;">
                    RESUME INSTALLATION
                </a>
            </div>
        </div>
        <?php
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        if (strpos($hook, 'vmpfence') === false) {
            return;
        }
        
        wp_enqueue_style(
            'vmpfence-admin',
            VMPFENCE_PLUGIN_URL . 'admin/assets/css/admin.css',
            array(),
            VMPFENCE_VERSION
        );
        
        // Enqueue scan options CSS for the scan options page
        if ($hook === 'admin_page_vmpfence-scan-options') {
            wp_enqueue_style(
                'vmpfence-scan-options',
                VMPFENCE_PLUGIN_URL . 'admin/assets/css/scan-options.css',
                array(),
                VMPFENCE_VERSION
            );
        }
        
        // Note: Login Security assets are enqueued in the view file (admin/views/login-security.php)
        // This prevents duplicate script loading and ensures the view owns its dependencies
        
        // Enqueue Audit Log assets (for both standalone page and Tools tab)
        $is_audit_log_page = $hook === 'vmp-wordpress-security_page_vmpfence-audit-log';
        $is_tools_audit_tab = $hook === 'vmp-wordpress-security_page_vmpfence-tools' && 
                              isset($_GET['tab']) && $_GET['tab'] === 'audit-log';
        
        if ($is_audit_log_page || $is_tools_audit_tab) {
            wp_enqueue_style(
                'vmpfence-audit-log-css',
                VMPFENCE_PLUGIN_URL . 'admin/assets/css/audit-log.css',
                array(),
                VMPFENCE_VERSION
            );
            
            wp_enqueue_script(
                'vmpfence-audit-log-js',
                VMPFENCE_PLUGIN_URL . 'admin/assets/js/audit-log.js',
                array('jquery'),
                VMPFENCE_VERSION,
                true
            );
            
            wp_localize_script('vmpfence-audit-log-js', 'vmpfenceAuditLog', array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('vmpfence_audit_log_nonce')
            ));
        }
        
        wp_enqueue_script(
            'vmpfence-admin',
            VMPFENCE_PLUGIN_URL . 'admin/assets/js/admin.js',
            array('jquery'),
            VMPFENCE_VERSION,
            true
        );
        
        // Localize admin script with settings
        wp_localize_script('vmpfence-admin', 'vmpfence_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('vmpfence_admin_nonce'),
            'pause_live_updates' => VMPFence_Config::get('pause_live_updates', 1),
            'update_interval' => VMPFence_Config::get('update_interval', 10),
            'i18n' => array(
                'saving'             => __('Saving...', 'vmpfence'),
                'saved'              => __('Settings saved.', 'vmpfence'),
                'error'              => __('An error occurred.', 'vmpfence'),
                'ajax_error'         => __('Request failed. Please try again.', 'vmpfence'),
                'processing'         => __('Processing...', 'vmpfence'),
                'starting_scan'      => __('Starting Scan...', 'vmpfence'),
                'start_scan'         => __('Start Scan', 'vmpfence'),
                'confirm_stop_scan'  => __('Are you sure you want to stop the scan?', 'vmpfence'),
                'scan_completed'     => __('Scan completed successfully.', 'vmpfence'),
                'scan_failed'        => __('Scan failed.', 'vmpfence'),
            )
        ));
    }
    
    /**
     * Dashboard page
     */
    public function dashboard_page() {
        $this->check_setup_and_redirect();
        include VMPFENCE_PLUGIN_DIR . 'admin/views/dashboard.php';
    }
    
    /**
     * Setup wizard page (delegates to setup wizard class)
     * @since 2.2.2
     */
    public function setup_wizard_page() {
        // Don't check setup here - this IS the setup page
        if (class_exists('VMPFence_Setup_Wizard')) {
            VMPFence_Setup_Wizard::render_setup_page();
        }
    }
    
    /**
     * Settings page
     */
    public function settings_page() {
        include VMPFENCE_PLUGIN_DIR . 'admin/views/settings.php';
    }
    
    /**
     * Firewall page
     * @since 2.0.0 -- Firewall Options View
     */
    public function firewall_page() {
        $this->check_setup_and_redirect();
        // Check if viewing different firewall views
        if (isset($_GET['view'])) {
            $view = sanitize_text_field($_GET['view']);
            
            switch ($view) {
                case 'options':
                    // Enqueue admin script for firewall options
                    wp_enqueue_script('jquery');
                    wp_enqueue_script(
                        'vmpfence-admin-js',
                        VMPFENCE_PLUGIN_URL . 'admin/assets/js/admin.js',
                        array('jquery'),
                        '1.0.0',
                        true
                    );
                    
                    include VMPFENCE_PLUGIN_DIR . 'admin/views/firewall-options.php';
                    break;
                case 'blocking-options':
                    // Blocking options settings page
                    include VMPFENCE_PLUGIN_DIR . 'admin/views/blocking-options.php';
                    break;
                case 'waf-rules':
                    // Redirect to firewall options with waf-rules hash (backward compatibility)
                    wp_redirect(admin_url('admin.php?page=vmpfence-firewall&view=options#waf-rules'));
                    exit;
                default:
                    include VMPFENCE_PLUGIN_DIR . 'admin/views/firewall.php';
                    break;
            }
        } else {
            include VMPFENCE_PLUGIN_DIR . 'admin/views/firewall.php';
        }
    }
    
    /**
     * Blocked IPs redirect (backward compatibility)
     */
    public function blocked_ips_redirect() {
        // Redirect to Firewall page with blocking tab
        wp_redirect(admin_url('admin.php?page=vmpfence-firewall&tab=blocking'));
        exit;
    }
    
    /**
     * Blocked IPs page (kept for direct access if needed)
     */
    public function blocked_ips_page() {
        include VMPFENCE_PLUGIN_DIR . 'admin/views/blocked-ips.php';
    }
    
    /**
     * Scanner page
     */
    public function scanner_page() {
        include VMPFENCE_PLUGIN_DIR . 'admin/views/scanner.php';
    }
    
    /**
     * Login security page
     */
    public function login_page() {
        include VMPFENCE_PLUGIN_DIR . 'admin/views/login.php';
    }
    
    /**
     * Scan page
     */
    public function scan_page() {
        $this->check_setup_and_redirect();
        include VMPFENCE_PLUGIN_DIR . 'admin/views/scan.php';
    }
    
    /**
     * Tools page
     */
    public function tools_page() {
        $this->check_setup_and_redirect();
        include VMPFENCE_PLUGIN_DIR . 'admin/views/tools.php';
    }
    
    /**
     * Audit Log page - Redirects to Tools section
     */
    public function audit_log_page() {
        $this->check_setup_and_redirect();
        ?>
        <script type="text/javascript">
            window.location.href = "<?php echo admin_url('admin.php?page=vmpfence-tools&tab=audit-log'); ?>";
        </script>
        <?php
    }
    
    /**
     * All Options page
     * @since 2.2.2 fixed function name conflict
     */
    public function all_options_page() {
        $this->check_setup_and_redirect();
        include VMPFENCE_PLUGIN_DIR . 'all-options/all-options.php';
    }
    
    /**
     * Help page
     */
    public function help_page() {
        $this->check_setup_and_redirect();
        include VMPFENCE_PLUGIN_DIR . 'admin/views/help.php';
    }
    
    /**
     * Logging & Analytics page
     */
    public function logging_analytics_page() {
        include VMPFENCE_PLUGIN_DIR . 'admin/logging-analytics.php';
    }
    
    /**
     * CVE Scanner page (Premium only)
     */
    public function cve_scanner_page() {
        if (!VMPFence_Config::is_api_available()) {
            echo '<div class="wrap"><h1>CVE Scanner</h1>';
            echo '<div class="notice notice-warning"><p><strong>Premium Feature:</strong> CVE Scanner requires an API connection. Please configure your API key in Settings.</p></div>';
            echo '</div>';
            return;
        }
        include VMPFENCE_PLUGIN_DIR . 'admin/pages/cve-scanner.php';
    }
    
    /**
     * YARA Deep Scan page (Premium only)
     */
    public function yara_scanner_page() {
        if (!VMPFence_Config::is_api_available()) {
            echo '<div class="wrap"><h1>YARA Deep Scan</h1>';
            echo '<div class="notice notice-warning"><p><strong>Premium Feature:</strong> YARA Deep Scan requires an API connection. Please configure your API key in Settings.</p></div>';
            echo '</div>';
            return;
        }
        include VMPFENCE_PLUGIN_DIR . 'admin/pages/yara-scanner.php';
    }
    
    /**
     * Login Security page
     */
    public function login_security_page() {
        $this->check_setup_and_redirect();
        include VMPFENCE_PLUGIN_DIR . 'admin/views/login-security.php';
    }
    
    /**
     * Scan Options page (hidden from menu)
     */
    public function scan_options_page() {
        $this->check_setup_and_redirect();
        // Enqueue scan options specific assets
        wp_enqueue_script(
            'vmpfence-scan-options-js',
            VMPFENCE_PLUGIN_URL . 'admin/assets/js/scan-options.js',
            array('jquery'),
            '1.0.0',
            true
        );
        
        // Localize script for AJAX
        wp_localize_script('vmpfence-scan-options-js', 'vmpfence_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('vmpfence_scan_options')
        ));
        
        include VMPFENCE_PLUGIN_DIR . 'admin/views/scan-options.php';
    }
    
    /**
     * AJAX handler for getting dashboard statistics
     * @since 2.2.2
     */
    public function ajax_get_dashboard_stats() {
        // Verify nonce
        check_ajax_referer('vmpfence_admin_nonce', 'nonce');
        
        // Verify capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Insufficient permissions', 'vmpfence-security')));
        }
        
        global $wpdb;
        
        // Get threats detected (from scan results)
        $threats_table = $wpdb->prefix . 'vmpfence_scan_results';
        $threats_detected = 0;
        if ($wpdb->get_var("SHOW TABLES LIKE '$threats_table'") === $threats_table) {
            $threats_detected = $wpdb->get_var("SELECT COUNT(*) FROM $threats_table");
        }
        
        // Get scans completed
        $scans_completed = get_option('vmpfence_total_scans_run', 0);
        
        // Get blocked attempts (from firewall logs)
        $firewall_table = $wpdb->prefix . 'vmpfence_waf_hits';
        $blocked_attempts = 0;
        if ($wpdb->get_var("SHOW TABLES LIKE '$firewall_table'") === $firewall_table) {
            $blocked_attempts = $wpdb->get_var("SELECT COUNT(*) FROM $firewall_table WHERE action LIKE '%blocked%'");
        }
        
        // Calculate uptime (days since plugin activation)
        $activation_time = get_option('vmpfence_activation_time');
        if ($activation_time) {
            $uptime_days = floor((time() - $activation_time) / (60 * 60 * 24));
            $uptime = $uptime_days . 'd';
        } else {
            $uptime = 'N/A';
        }
        
        // Determine overall status
        $overall_status = 'healthy';
        if ($threats_detected > 10) {
            $overall_status = 'critical';
        } elseif ($threats_detected > 0) {
            $overall_status = 'warning';
        }
        
        wp_send_json_success(array(
            'threats_detected' => $threats_detected,
            'scans_completed' => $scans_completed,
            'blocked_attempts' => $blocked_attempts,
            'uptime' => $uptime,
            'overall_status' => $overall_status
        ));
    }
}

// Initialize dashboard
new VMPFence_Dashboard();
