<?php
defined('ABSPATH') || exit;

/**
 * Activity Log Hooks for WPFort Security Plugin
 * 
 * Integrates with WordPress hooks to capture security-relevant activities.
 */

// Log login attempts
add_filter('wp_login', function($user_login, $user) {
    wpsec_log_login_attempt(true, $user_login);
    return $user_login;
}, 10, 2);

add_action('wp_login_failed', function($username) {
    wpsec_log_login_attempt(false, $username);
});

// Two-factor authentication attempts (if using)
add_action('two_factor_authentication_attempt', function($user, $success) {
    $event_type = 'two_factor_auth';
    $severity = $success ? WPSEC_LOG_INFO : WPSEC_LOG_WARNING;
    $status = $success ? 'successful' : 'failed';
    $description = sprintf('Two-factor authentication %s for user %s', $status, $user->user_login);
    
    wpsec_add_to_activity_log(
        $event_type,
        $description,
        $severity,
        $status,
        'user',
        $user->ID,
        $user->ID,
        $user->user_login
    );
}, 10, 2);

// User role changes
add_action('set_user_role', function($user_id, $new_role, $old_roles) {
    $old_role = !empty($old_roles) ? implode(', ', $old_roles) : 'none';
    wpsec_log_role_change($user_id, $old_role, $new_role);
}, 10, 3);

// User creation and deletion
add_action('user_register', function($user_id) {
    $user = get_userdata($user_id);
    wpsec_add_to_activity_log(
        'user_created',
        sprintf('New user created: %s (ID: %d)', $user->user_login, $user_id),
        WPSEC_LOG_WARNING,
        'created',
        'user',
        $user_id
    );
});

add_action('delete_user', function($user_id) {
    $user = get_userdata($user_id);
    wpsec_add_to_activity_log(
        'user_deleted',
        sprintf('User deleted: %s (ID: %d)', $user->user_login, $user_id),
        WPSEC_LOG_WARNING,
        'deleted',
        'user',
        $user_id
    );
});

// Plugin activation and deactivation
add_action('activated_plugin', function($plugin) {
    wpsec_log_plugin_toggle($plugin, true);
});

add_action('deactivated_plugin', function($plugin) {
    wpsec_log_plugin_toggle($plugin, false);
});

// Plugin installation and deletion
add_action('upgrader_process_complete', function($upgrader, $options) {
    // Check if this is a plugin installation
    if ($options['action'] == 'install' && $options['type'] == 'plugin') {
        $plugin_info = $upgrader->skin->api->name ?? 'Unknown plugin';
        wpsec_add_to_activity_log(
            'plugin_installed',
            sprintf('Plugin installed: %s', $plugin_info),
            WPSEC_LOG_WARNING,
            'installed',
            'plugin',
            $plugin_info
        );
    }
    
    // Check if this is a WordPress core, plugin, or theme update
    if ($options['action'] == 'update') {
        $type = $options['type'];
        
        if ($type == 'core') {
            $old_version = get_bloginfo('version');
            $upgrader->core_upgrade($options['plugins']);
            $new_version = get_bloginfo('version');
            
            wpsec_log_system_update('core', 'WordPress', $old_version, $new_version);
        } 
        else if ($type == 'plugin' && !empty($options['plugins'])) {
            foreach ($options['plugins'] as $plugin_file) {
                $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_file);
                $plugin_name = $plugin_data['Name'] ?? basename($plugin_file, '.php');
                $new_version = $plugin_data['Version'] ?? 'unknown';
                
                wpsec_log_system_update('plugin', $plugin_name, 'previous version', $new_version);
            }
        }
        else if ($type == 'theme' && !empty($options['themes'])) {
            foreach ($options['themes'] as $theme_slug) {
                $theme = wp_get_theme($theme_slug);
                wpsec_log_system_update('theme', $theme->get('Name'), 'previous version', $theme->get('Version'));
            }
        }
    }
}, 10, 2);

add_action('delete_plugin', function($plugin_file) {
    $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_file);
    $plugin_name = $plugin_data['Name'] ?? basename($plugin_file, '.php');
    
    wpsec_add_to_activity_log(
        'plugin_deleted',
        sprintf('Plugin deleted: %s', $plugin_name),
        WPSEC_LOG_WARNING,
        'deleted',
        'plugin',
        $plugin_file
    );
});

// Theme installation, switching, and deletion
add_action('switch_theme', function($new_theme_name, $new_theme) {
    $old_theme = wp_get_theme();
    
    wpsec_add_to_activity_log(
        'theme_switched',
        sprintf('Theme switched from %s to %s', $old_theme->get('Name'), $new_theme_name),
        WPSEC_LOG_INFO,
        'switched',
        'theme',
        $new_theme->get_stylesheet()
    );
}, 10, 2);

add_action('delete_theme', function($theme_slug) {
    $theme = wp_get_theme($theme_slug);
    
    wpsec_add_to_activity_log(
        'theme_deleted',
        sprintf('Theme deleted: %s', $theme->get('Name')),
        WPSEC_LOG_WARNING,
        'deleted',
        'theme',
        $theme_slug
    );
});

// File upload monitoring
add_filter('wp_handle_upload', function($file) {
    $file_path = $file['file'];
    $file_type = $file['type'];
    $relative_path = str_replace(ABSPATH, '', $file_path);
    
    $severity = WPSEC_LOG_INFO;
    
    // Check if this is a PHP or executable file (higher risk)
    if (preg_match('/\.(php|phtml|php[3-7]|sh|exe|bat|cmd)$/i', $file_path)) {
        $severity = WPSEC_LOG_CRITICAL;
    }
    
    wpsec_add_to_activity_log(
        'file_uploaded',
        sprintf('File uploaded: %s (Type: %s)', $relative_path, $file_type),
        $severity,
        'uploaded',
        'file',
        $relative_path
    );
    
    return $file;
});

// File edits within WordPress admin
add_action('wp_ajax_edit-theme-plugin-file', function() {
    if (isset($_POST['file'])) {
        $file = sanitize_text_field($_POST['file']);
        $relative_path = str_replace(ABSPATH, '', $file);
        
        wpsec_log_file_modification($file, 'edited');
    }
}, 0);

// Core file modifications
add_action('wpsec_core_file_modified', function($file_path) {
    wpsec_log_file_modification($file_path, 'modified');
});

// Scan related hooks
add_action('wpsec_scan_started', function($scan_id) {
    wpsec_log_security_scan($scan_id, 'started');
});

add_action('wpsec_scan_completed', function($scan_id, $results) {
    wpsec_log_security_scan($scan_id, 'completed', $results);
}, 10, 2);

// Firewall related hooks
add_action('wpsec_firewall_blocked', function($rule_id, $ip, $request_data) {
    wpsec_log_firewall_event($rule_id, $ip, $request_data);
});

// Malware cleanup actions
add_action('wpsec_malware_cleaned', function($file_path, $action) {
    $relative_path = str_replace(ABSPATH, '', $file_path);
    
    wpsec_add_to_activity_log(
        'malware_action',
        sprintf('Malware action performed on %s: %s', $relative_path, $action),
        WPSEC_LOG_CRITICAL,
        $action,
        'file',
        $relative_path
    );
});

// Plugin settings changes (specifically for this security plugin)
// Use the init hook to ensure WordPress is fully loaded before registering this hook
add_action('init', function() {
    add_action('update_option', function($option_name, $old_value, $new_value) {
        // Only log settings changes for our plugin
        if (strpos($option_name, 'wpsec_') === 0) {
            // Don't log sensitive info or internal state options
            $sensitive_options = ['wpsec_api_key', 'wpsec_current_scan_id'];
            if (in_array($option_name, $sensitive_options)) {
                return;
            }
            
            $old_value_str = is_array($old_value) ? 'array' : (is_object($old_value) ? 'object' : (string) $old_value);
            $new_value_str = is_array($new_value) ? 'array' : (is_object($new_value) ? 'object' : (string) $new_value);
            
            wpsec_add_to_activity_log(
                'settings_changed',
                sprintf('Security plugin setting changed: %s from %s to %s', 
                    str_replace('wpsec_', '', $option_name), 
                    substr($old_value_str, 0, 50), 
                    substr($new_value_str, 0, 50)
                ),
                WPSEC_LOG_INFO,
                'changed',
                'setting',
                $option_name
            );
        }
    }, 10, 3);
});

// REST API access logging for this plugin's endpoints
add_filter('rest_request_before_callbacks', function($response, $handler, $request) {
    $route = $request->get_route();
    
    // Only log requests to our plugin's endpoints
    if (strpos($route, '/wpsec/v1/') === 0) {
        $method = $request->get_method();
        $endpoint = str_replace('/wpsec/v1/', '', $route);
        
        // Don't log activity-log endpoints to avoid recursion
        if (strpos($endpoint, 'activity-log') === 0) {
            return $response;
        }
        
        wpsec_add_to_activity_log(
            'api_request',
            sprintf('REST API request: %s %s', $method, $endpoint),
            WPSEC_LOG_INFO,
            'request',
            'api',
            $endpoint
        );
    }
    
    return $response;
}, 10, 3);

// Log cron job triggers related to security
add_action('wpsec_run_background_scan', function() {
    wpsec_add_to_activity_log(
        'cron_triggered',
        'Security scan cron job triggered',
        WPSEC_LOG_INFO,
        'triggered',
        'cron',
        'background_scan'
    );
}, 0);

add_action('wpsec_process_backup', function($backup_type, $backup_id) {
    wpsec_add_to_activity_log(
        'backup_started',
        sprintf('Backup process started: %s (ID: %s)', $backup_type, $backup_id),
        WPSEC_LOG_INFO,
        'started',
        'backup',
        $backup_id
    );
}, 0, 2);
