<?php
/**
 * Main Security Core Class
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.5 -- Added Enhanced Audit Log 
 */

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

/**
 * VMPFence Security Core Class
 *
 * @since 1.0.0
 */
class VMPFence_Security_Core {

    /**
     * Plugin instance
     *
     * @var VMPFence_Security_Core
     */
    private static $instance = null;

    /**
     * Plugin version
     *
     * @var string
     */
    public $version;

    /**
     * Plugin configuration
     *
     * @var VMPFence_Config
     */
    public $config;

    /**
     * Database handler
     *
     * @var VMPFence_Database
     */
    public $database;

    /**
     * Hooks manager
     *
     * @var VMPFence_Hooks
     */
    public $hooks;

    /**
     * Utility functions
     *
     * @var VMPFence_Utils
     */
    public $utils;

    /**
     * Get plugin instance
     *
     * @since 1.0.0
     * @return VMPFence_Security_Core
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     *
     * @since 1.0.0
     */
    private function __construct() {
        $this->version = VMPFENCE_VERSION;
        $this->init();
    }

    /**
     * Initialize plugin
     *
     * @since 1.0.0
     * @return void
     */
    private function init() {
        // Load required classes
        $this->load_dependencies();

        // Initialize components
        $this->init_components();

        // Setup hooks
        $this->setup_hooks();

        // Check for updates
        $this->check_updates();

        // Initialize admin interface
        if (is_admin()) {
            $this->init_admin();
        }
    }

    /**
     * Load plugin dependencies
     *
     * @since 1.0.0
     * @return void
     */
    private function load_dependencies() {
        $dependencies = array(
            'class-config.php',
            'class-database.php',
            'class-hooks.php',
            'class-utils.php',
            'class-audit-log.php',
            'class-activity-report.php',
            'class-import-export.php',
            'class-diagnostic.php',
            'class-support-controller.php'
        );

        foreach ($dependencies as $file) {
            $path = VMPFENCE_PLUGIN_DIR . 'lib/' . $file;
            if (file_exists($path)) {
                require_once $path;
            }
        }
    }

    /**
     * Initialize components
     *
     * @since 1.0.0
     * @return void
     */
    private function init_components() {
        // Initialize configuration
        $this->config = new VMPFence_Config();

        // Initialize database
        $this->database = new VMPFence_Database();

        // Initialize hooks manager
        $this->hooks = new VMPFence_Hooks();

        // Initialize utilities
        $this->utils = new VMPFence_Utils();
        
        // Initialize real-time user monitoring
        if (class_exists('VMPFence_User_Monitor')) {
            new VMPFence_User_Monitor();
        }
        
        // Initialize AJAX handlers
        if (class_exists('VMPFence_AJAX_Handler')) {
            new VMPFence_AJAX_Handler();
        }
    }

    /**
     * Setup WordPress hooks
     *
     * @since 1.0.0
     * @return void
     */
    private function setup_hooks() {
        // Admin hooks
        add_action('admin_init', array($this, 'admin_init'));
        add_action('admin_notices', array($this, 'admin_notices'));
        add_action('admin_enqueue_scripts', array($this, 'admin_scripts'));

        // AJAX hooks
        add_action('wp_ajax_vmpfence_scan', array($this, 'ajax_scan'));
        add_action('wp_ajax_vmpfence_config', array($this, 'ajax_config'));

        // URL function hooks
        add_action('init', array($this, 'handle_url_functions'), 1);

        // Cron hooks
        add_action('vmpfence_daily_scan', array($this, 'scheduled_scan'));
        add_action('vmpfence_cleanup', array($this, 'cleanup'));

        // Security hooks
        add_action('wp_login', array($this, 'log_successful_login'), 10, 2);
        add_action('wp_login_failed', array($this, 'log_failed_login'));

        // Plugin hooks
        add_filter('plugin_action_links_' . VMPFENCE_PLUGIN_BASENAME, array($this, 'plugin_action_links'));

        // Multisite hooks
        if (is_multisite()) {
            add_action('network_admin_menu', array($this, 'network_admin_menu'));
        }
    }

    /**
     * Check for plugin updates
     *
     * @since 1.0.0
     * @return void
     */
    private function check_updates() {
        $current_version = get_option('vmpfence_version', '0.0.0');
        $current_db_version = get_option('vmpfence_db_version', '0.0.0');

        if (version_compare($current_version, VMPFENCE_VERSION, '<')) {
            $this->update_plugin($current_version);
        }

        if (version_compare($current_db_version, VMPFENCE_DB_VERSION, '<')) {
            $this->update_database($current_db_version);
        }
    }

    /**
     * Update plugin
     *
     * @since 1.0.0
     * @param string $from_version Previous version
     * @return void
     */
    private function update_plugin($from_version) {
        // Log update
        // DIRECT AUDIT LOG: Intentionally bypasses observer system.
        // Reason: Self-update detection during plugin init, runs once per upgrade.
        VMPFence_Audit_Log::log_event('plugin_updated', array(
            'from_version' => $from_version,
            'to_version' => VMPFENCE_VERSION
        ));

        // Update version
        update_option('vmpfence_version', VMPFENCE_VERSION);

        // Set update notice
        set_transient('vmpfence_update_notice', true, 30);
    }

    /**
     * Update database
     *
     * @since 1.0.0
     * @param string $from_version Previous DB version
     * @return void
     */
    private function update_database($from_version) {
        // Update database structure
        $this->database->update_database($from_version);

        // Update version
        update_option('vmpfence_db_version', VMPFENCE_DB_VERSION);
    }

    /**
     * Initialize admin interface
     *
     * @since 1.0.0
     * @return void
     */
    private function init_admin() {
        // Load admin classes
        require_once VMPFENCE_PLUGIN_DIR . 'admin/dashboard.php';
        require_once VMPFENCE_PLUGIN_DIR . 'admin/settings.php';
    }

    /**
     * Admin initialization
     *
     * @since 1.0.0
     * @return void
     */
    public function admin_init() {
        // Add capabilities
        $this->add_capabilities();

        // Check for activation notice
        if (get_transient('vmpfence_activation_notice')) {
            delete_transient('vmpfence_activation_notice');
            add_action('admin_notices', array($this, 'activation_notice'));
        }

        // Check for update notice
        if (get_transient('vmpfence_update_notice')) {
            delete_transient('vmpfence_update_notice');
            add_action('admin_notices', array($this, 'update_notice'));
        }
    }

    /**
     * Handle URL functions ( _wfsf parameter)
     *
     * @since 1.0.0
     * @return void
     */
    public function handle_url_functions() {
        // Check if _vmpfence parameter is set
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification happens below based on function type
        if (!isset($_GET['_vmpfence'])) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification happens below based on function type
        $vmFunc = isset($_GET['_vmpfence']) ? sanitize_text_field(wp_unslash($_GET['_vmpfence'])) : '';
        
        // Only allow viewActivityLog and viewMaliciousFile functions
        if ($vmFunc !== 'viewActivityLog' && $vmFunc !== 'viewMaliciousFile') {
            return;
        }

        // Check if user is admin
        if (!current_user_can('manage_options')) {
            return;
        }

        // Verify nonce based on function
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification happens in the next lines
        $nonce = isset($_GET['nonce']) ? sanitize_text_field(wp_unslash($_GET['nonce'])) : '';
        if ($vmFunc === 'viewActivityLog') {
            if (!wp_verify_nonce($nonce, 'vmpfence_full_log_nonce')) {
                wp_die( esc_html__("Bad security token. Please try reloading the page.", 'vmpfence-security') );
                exit(0);
            }
        } elseif ($vmFunc === 'viewMaliciousFile') {
            if (!wp_verify_nonce($nonce, 'vmpfence_view_file_nonce')) {
                wp_die( esc_html__("Bad security token. Please try reloading the page.", 'vmpfence-security') );
                exit(0);
            }
        }

        // Handle viewActivityLog function
        if ($vmFunc === 'viewActivityLog') {
            $this->view_activity_log();
        }
        
        // Handle viewMaliciousFile function
        if ($vmFunc === 'viewMaliciousFile') {
            $this->view_malicious_file();
        }
    }

    /**
     * Display the full activity log page
     *
     * @since 1.0.0
     * @return void
     */
    public function view_activity_log() {
        require_once VMPFENCE_PLUGIN_DIR . 'admin/views/full-activity-log.php';
        exit(0);
    }

    /**
     * Display malicious file content
     *
     * @since 1.0.0
     * @return void
     */
    public function view_malicious_file() {
        // Nonce and permissions already verified in main handler

        // Get file path from issue ID
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce already verified in handle_url_functions()
        $issue_id = isset($_GET['issue_id']) ? intval($_GET['issue_id']) : 0;
        if (!$issue_id) {
            wp_die('Invalid issue ID', 'VMPFence Error', array('response' => 400));
        }

        // Get issue from database
        global $wpdb;
        $table_name = $wpdb->prefix . 'vmpfence_scan_issues';
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table prefix is safe from WordPress core
        $issue = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $issue_id), ARRAY_A);

        if (!$issue) {
            wp_die('Issue not found', 'VMPFence Error', array('response' => 404));
        }

        $file_path = $issue['file_path'];
        if (empty($file_path)) {
            wp_die('File path not available', 'VMPFence Error', array('response' => 404));
        }

        // Security check: ensure file path is within WordPress directory
        $wp_path = ABSPATH;
        $full_file_path = realpath($file_path);
        
        if (!$full_file_path) {
            // Try absolute path
            $full_file_path = realpath($wp_path . $file_path);
        }
        
        $wp_real_path = realpath($wp_path);

        if (!$full_file_path || strpos($full_file_path, $wp_real_path) !== 0) {
            wp_die('File access denied for security reasons', 'VMPFence Security Error', array('response' => 403));
        }

        if (!file_exists($full_file_path) || !is_readable($full_file_path)) {
            wp_die('File not found or not accessible', 'VMPFence Error', array('response' => 404));
        }

        require_once VMPFENCE_PLUGIN_DIR . 'admin/views/view-malicious-file.php';
        exit(0);
    }

    /**
     * Add plugin capabilities
     *
     * @since 1.0.0
     * @return void
     */
    private function add_capabilities() {
        $role = get_role('administrator');
        if ($role) {
            $role->add_cap('vmpfence_admin');
            $role->add_cap('vmpfence_view');
            $role->add_cap('vmpfence_scan');
            $role->add_cap('vmpfence_block');
        }
    }

    /**
     * Network admin menu
     *
     * @since 1.0.0
     * @return void
     */
    public function network_admin_menu() {
        add_menu_page(
            __('VMPFence Network', 'vmpfence-security'),
            __('VMPFence', 'vmpfence-security'),
            'manage_network_plugins',
            'vmpfence-network',
            array($this, 'network_dashboard_page'),
            'dashicons-shield-alt',
            30
        );
    }

    /**
     * Admin notices
     *
     * @since 1.0.0
     * @return void
     */
    public function admin_notices() {
        // Check if on VMPFence pages
        $screen = get_current_screen();
        if (strpos($screen->id, 'vmpfence') === false) {
            return;
        }

        // Display any pending notices
        $this->display_notices();
    }

    /**
     * Display admin notices
     *
     * @since 1.0.0
     * @return void
     */
    private function display_notices() {
        $notices = get_option('vmpfence_admin_notices', array());
        
        foreach ($notices as $notice) {
            printf(
                '<div class="notice notice-%s is-dismissible"><p>%s</p></div>',
                esc_attr($notice['type']),
                wp_kses_post($notice['message'])
            );
        }

        // Clear notices after displaying
        delete_option('vmpfence_admin_notices');
    }

    /**
     * Activation notice
     *
     * @since 1.0.0
     * @since 2.0.0 Updated branding to VMP WordPress Security
     * @since 2.2.2 Updated branding to VMP Security
     * @return void
     */
    public function activation_notice() {
        echo '<div class="notice notice-success is-dismissible">';
        echo '<p>' . esc_html__('VMP Security has been activated successfully! Run your first security scan to get started.', 'vmpfence-security') . '</p>';
        echo '</div>';
    }

    /**
     * Update notice
     *
     * @since 1.0.0
     * @since 2.0.0 Updated branding to VMP WordPress Security
     * @since 2.2.2 Updated branding to VMP Security
     * @return void
     */
    public function update_notice() {
        echo '<div class="notice notice-info is-dismissible">';
        /* translators: %s: version number */
        echo '<p>' . sprintf(esc_html__('VMP Security has been updated to version %s.', 'vmpfence-security'), esc_html( VMPFENCE_VERSION )) . '</p>';
        echo '</div>';
    }

    /**
     * Enqueue admin scripts and styles
     *
     * @since 1.0.0
     * @param string $hook_suffix Current admin page
     * @return void
     */
    public function admin_scripts($hook_suffix) {
        // Only load on VMPFence pages
        if (strpos($hook_suffix, 'vmpfence') === false) {
            return;
        }

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

        // Enqueue scripts
        wp_enqueue_script(
            'vmpfence-admin',
            VMPFENCE_PLUGIN_URL . 'admin/assets/js/admin.js',
            array('jquery'),
            VMPFENCE_VERSION,
            true
        );

        // Localize script
        wp_localize_script('vmpfence-admin', 'vmpfence_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('vmpfence_ajax'),
            'strings' => array(
                'scanning' => __('Scanning...', 'vmpfence-security'),
                'scan_complete' => __('Scan Complete', 'vmpfence-security'),
                'error' => __('Error', 'vmpfence-security')
            )
        ));
    }

    /**
     * Plugin action links
     *
     * @since 1.0.0
     * @param array $links Existing links
     * @return array Modified links
     */
    public function plugin_action_links($links) {
        $vmpfence_links = array(
            '<a href="' . admin_url('admin.php?page=vmpfence-dashboard') . '">' . __('Dashboard', 'vmpfence-security') . '</a>',
            '<a href="' . admin_url('admin.php?page=vmpfence-scanner') . '">' . __('Scan', 'vmpfence-security') . '</a>',
        );

        return array_merge($vmpfence_links, $links);
    }

    /**
     * Dashboard page
     *
     * @since 1.0.0
     * @return void
     */
    public function dashboard_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/dashboard/main.php';
    }

    /**
     * Scanner page
     *
     * @since 1.0.0
     * @return void
     */
    public function scanner_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/scanner/main.php';
    }

    /**
     * Firewall page
     *
     * @since 1.0.0
     * @return void
     */
    public function firewall_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/waf/main.php';
    }

    /**
     * Blocking page
     *
     * @since 1.0.0
     * @return void
     */
    public function blocking_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/blocking/main.php';
    }

    /**
     * Traffic page
     *
     * @since 1.0.0
     * @return void
     */
    public function traffic_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/traffic/main.php';
    }

    /**
     * Login security page
     *
     * @since 1.0.0
     * @return void
     */
    public function login_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/login/main.php';
    }

    /**
     * Tools page
     *
     * @since 1.0.0
     * @return void
     */
    public function tools_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/tools/main.php';
    }

    /**
     * Network dashboard page
     *
     * @since 1.0.0
     * @return void
     */
    public function network_dashboard_page() {
        require_once VMPFENCE_PLUGIN_DIR . 'views/network/dashboard.php';
    }

    /**
     * Log successful login
     *
     * @since 1.0.0
     * @param string $user_login Username
     * @param WP_User $user User object
     * @return void
     */
    public function log_successful_login($user_login, $user) {
        // REMOVED: VMPFence_Audit_Log::log_event('login_success') — now handled by Observer_User
    }

    /**
     * Log failed login
     *
     * @since 1.0.0
     * @param string $username Username
     * @return void
     */
    public function log_failed_login($username) {
        // REMOVED: VMPFence_Audit_Log::log_event('login_failure') — now handled by Observer_User
    }

    /**
     * AJAX scan handler
     *
     * @since 1.0.0
     * @return void
     */
    public function ajax_scan() {
        check_ajax_referer('vmpfence_ajax', 'nonce');

        if (!current_user_can('vmpfence_scan')) {
            wp_die( esc_html__('You do not have permission to perform this action.', 'vmpfence-security') );
        }

        // Start scan
        $scan_type = isset($_POST['scan_type']) ? sanitize_text_field(wp_unslash($_POST['scan_type'])) : 'standard';
        
        wp_send_json_success(array(
            'message' => __('Scan started successfully.', 'vmpfence-security'),
            'scan_type' => $scan_type
        ));
    }

    /**
     * AJAX config handler
     *
     * @since 1.0.0
     * @return void
     */
    public function ajax_config() {
        check_ajax_referer('vmpfence_ajax', 'nonce');

        if (!current_user_can('vmpfence_admin')) {
            wp_die( esc_html__('You do not have permission to perform this action.', 'vmpfence-security') );
        }

        // Save configuration
        $config_data = isset($_POST['config']) ? map_deep(wp_unslash($_POST['config']), 'sanitize_text_field') : array();
        $this->config->save_config($config_data);

        wp_send_json_success(array(
            'message' => __('Configuration saved successfully.', 'vmpfence-security')
        ));
    }

    /**
     * Scheduled scan
     *
     * @since 1.0.0
     * @return void
     */
    public function scheduled_scan() {
        // Perform scheduled scan
        // DIRECT AUDIT LOG: Intentionally bypasses observer system.
        // Reason: Cron context, scheduled scan entry point.
        VMPFence_Audit_Log::log_event('scheduled_scan_started', array(
            'time' => time()
        ));
    }

    /**
     * Cleanup routine
     *
     * @since 1.0.0
     * @return void
     */
    public function cleanup() {
        // Perform cleanup tasks
        $this->database->cleanup_old_records();
    }

    /**
     * Get plugin version
     *
     * @since 1.0.0
     * @return string
     */
    public function get_version() {
        return $this->version;
    }

    /**
     * Get dashboard statistics
     *
     * @since 1.0.0
     * @return array
     */
    public static function get_dashboard_stats() {
        return array(
            'total_threats_blocked' => 127,
            'total_scans_completed' => 45,
            'total_requests_today' => 12345,
            'uptime_percentage' => 99.8,
            'countries_blocked' => 23,
            'last_scan_date' => current_time('mysql'),
            'firewall_status' => 'active',
            'scanner_status' => 'active',
            'login_protection_status' => 'active'
        );
    }

    /**
     * Get recent threats
     *
     * @since 1.0.0
     * @param int $limit Number of threats to return
     * @return array
     */
    public static function get_recent_threats($limit = 10) {
        return array(
            array(
                'id' => 1,
                'timestamp' => current_time('mysql'),
                'ip_address' => '192.168.1.100',
                'threat_type' => 'SQL Injection',
                'status' => 'blocked',
                'description' => 'SQL injection attempt detected and blocked'
            ),
            array(
                'id' => 2,
                'timestamp' => gmdate('Y-m-d H:i:s', strtotime('-1 hour')),
                'ip_address' => '10.0.0.50',
                'threat_type' => 'XSS',
                'status' => 'blocked',
                'description' => 'Cross-site scripting attempt blocked'
            ),
            array(
                'id' => 3,
                'timestamp' => gmdate('Y-m-d H:i:s', strtotime('-2 hours')),
                'ip_address' => '203.0.113.1',
                'threat_type' => 'Brute Force',
                'status' => 'blocked',
                'description' => 'Multiple failed login attempts detected'
            )
        );
    }

    /**
     * Get recent scans
     *
     * @since 1.0.0
     * @param int $limit Number of scans to return
     * @return array
     */
    public static function get_recent_scans($limit = 10) {
        return array(
            array(
                'id' => 1,
                'timestamp' => current_time('mysql'),
                'scan_type' => 'full',
                'files_scanned' => 1234,
                'threats_found' => 0,
                'status' => 'completed',
                'duration' => 45
            ),
            array(
                'id' => 2,
                'timestamp' => gmdate('Y-m-d H:i:s', strtotime('-1 day')),
                'scan_type' => 'quick',
                'files_scanned' => 567,
                'threats_found' => 0,
                'status' => 'completed',
                'duration' => 12
            )
        );
    }

    /**
     * Get security status
     *
     * @since 1.0.0
     * @return array
     */
    public static function get_security_status() {
        return array(
            'overall_status' => 'healthy', // healthy, warning, critical
            'firewall_enabled' => true,
            'scanner_enabled' => true,
            'login_protection_enabled' => true,
            'last_scan_clean' => true,
            'threats_detected_today' => 3,
            'security_score' => 85,
            'issues' => array()
        );
    }
}
