<?php
if (!defined('ABSPATH')) {
    exit;
}

function moesec_hardening_tab() {
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'moesec'));
    }

    if (isset($_POST['moesec_apply_hardening']) && check_admin_referer('moesec_hardening', 'moesec_hardening_nonce')) {
        moesec_apply_hardening_measures();
    }
    
    $disable_file_editing = defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT;
    $hide_wp_version = get_option('moesec_hide_wp_version', false);
    $disable_xmlrpc = get_option('moesec_disable_xmlrpc', false);
    $disable_user_enumeration = get_option('moesec_disable_user_enumeration', false);
    $disable_php_in_uploads = get_option('moesec_disable_php_in_uploads', false);
    $custom_admin_url = get_option('moesec_custom_admin_url', '');
    $emergency_key = get_option('moesec_emergency_key', wp_generate_password(16, false));
    
    // Generate emergency URL
    $emergency_url = !empty($custom_admin_url) ? 
        home_url('/wp-login.php?moesec_emergency=' . $emergency_key) : '';
    
    ?>
    <h3><?php esc_html_e('WordPress Hardening', 'moesec'); ?></h3>
    
    <div class="moesec-hardening-status" style="background: #f0f0f0; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <h4><?php esc_html_e('Current Security Status', 'moesec'); ?></h4>
        <table class="widefat">
            <thead>
                <tr>
                    <th><?php esc_html_e('Security Measure', 'moesec'); ?></th>
                    <th><?php esc_html_e('Status', 'moesec'); ?></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><?php esc_html_e('File Editing', 'moesec'); ?></td>
                    <td>
                        <?php if ($disable_file_editing): ?>
                            <span style="color: #46b450;">✓ <?php esc_html_e('Disabled', 'moesec'); ?></span>
                        <?php else: ?>
                            <span style="color: #d63638;">✗ <?php esc_html_e('Enabled', 'moesec'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><?php esc_html_e('WordPress Version Display', 'moesec'); ?></td>
                    <td>
                        <?php if ($hide_wp_version): ?>
                            <span style="color: #46b450;">✓ <?php esc_html_e('Hidden', 'moesec'); ?></span>
                        <?php else: ?>
                            <span style="color: #d63638;">✗ <?php esc_html_e('Visible', 'moesec'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><?php esc_html_e('XML-RPC', 'moesec'); ?></td>
                    <td>
                        <?php if ($disable_xmlrpc): ?>
                            <span style="color: #46b450;">✓ <?php esc_html_e('Disabled', 'moesec'); ?></span>
                        <?php else: ?>
                            <span style="color: #d63638;">✗ <?php esc_html_e('Enabled', 'moesec'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><?php esc_html_e('User Enumeration', 'moesec'); ?></td>
                    <td>
                        <?php if ($disable_user_enumeration): ?>
                            <span style="color: #46b450;">✓ <?php esc_html_e('Blocked', 'moesec'); ?></span>
                        <?php else: ?>
                            <span style="color: #d63638;">✗ <?php esc_html_e('Allowed', 'moesec'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><?php esc_html_e('PHP Execution in Uploads', 'moesec'); ?></td>
                    <td>
                        <?php if ($disable_php_in_uploads): ?>
                            <span style="color: #46b450;">✓ <?php esc_html_e('Disabled', 'moesec'); ?></span>
                        <?php else: ?>
                            <span style="color: #d63638;">✗ <?php esc_html_e('Allowed', 'moesec'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><?php esc_html_e('Custom Admin URL', 'moesec'); ?></td>
                    <td>
                        <?php if (!empty($custom_admin_url)): ?>
                            <span style="color: #46b450;">✓ <?php esc_html_e('Active', 'moesec'); ?></span>
                        <?php else: ?>
                            <span style="color: #d63638;">✗ <?php esc_html_e('Not Set', 'moesec'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <form method="post" action="">
        <?php wp_nonce_field('moesec_hardening', 'moesec_hardening_nonce'); ?>
        <table class="form-table">
            <tr>
                <th><?php esc_html_e('Disable File Editing', 'moesec'); ?></th>
                <td>
                    <input type="checkbox" name="disable_file_editing" <?php checked($disable_file_editing); ?>>
                    <p class="description"><?php esc_html_e('Prevents editing of theme and plugin files from the WordPress admin.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Hide WordPress Version', 'moesec'); ?></th>
                <td>
                    <input type="checkbox" name="hide_wp_version" <?php checked($hide_wp_version); ?>>
                    <p class="description"><?php esc_html_e('Removes WordPress version from your site\'s HTML.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="disable_xmlrpc"><?php esc_html_e('Disable XML-RPC', 'moesec'); ?></label></th>
                <td>
                    <input type="checkbox" id="disable_xmlrpc" name="disable_xmlrpc" <?php checked($disable_xmlrpc); ?>>
                    <p class="description"><?php esc_html_e('Disables XML-RPC functionality which can be exploited for brute force attacks and DDoS. Note: This may affect some plugins and mobile apps.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Disable User Enumeration', 'moesec'); ?></th>
                <td>
                    <input type="checkbox" name="disable_user_enumeration" <?php checked($disable_user_enumeration); ?>>
                    <p class="description"><?php esc_html_e('Prevents attackers from discovering usernames via REST API and author archives.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Disable PHP Execution in Uploads', 'moesec'); ?></th>
                <td>
                    <input type="checkbox" name="disable_php_in_uploads" <?php checked($disable_php_in_uploads); ?>>
                    <p class="description"><?php esc_html_e('Prevents PHP files from being executed in the uploads directory.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Custom Admin URL', 'moesec'); ?></th>
                <td>
                    <input type="text" 
                           name="custom_admin_url" 
                           value="<?php echo esc_attr($custom_admin_url); ?>" 
                           placeholder="my-secure-admin" 
                           class="regular-text">
                    <p class="description">
                        <?php esc_html_e('Change wp-admin/wp-login.php to a custom URL (leave empty to disable). Only lowercase letters, numbers, and hyphens.', 'moesec'); ?><br>
                        <strong style="color: #d63638;">
                            <?php esc_html_e('⚠️ IMPORTANT: Save this URL! You will NOT be able to access wp-admin or wp-login.php directly after enabling this.', 'moesec'); ?>
                        </strong>
                    </p>
                    <?php if (!empty($custom_admin_url)): ?>
                    <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-top: 10px;">
                        <p style="margin: 0;">
                            <strong><?php esc_html_e('Your Custom Admin URL:', 'moesec'); ?></strong><br>
                            <code style="font-size: 16px; background: #fff; padding: 8px 12px; display: inline-block; margin-top: 5px;">
                                <?php echo esc_html(home_url('/' . $custom_admin_url)); ?>
                            </code>
                        </p>
                        <p style="margin: 10px 0 0 0;">
                            <strong><?php esc_html_e('Emergency Access URL:', 'moesec'); ?></strong><br>
                            <code style="font-size: 14px; background: #fff; padding: 6px 10px; display: inline-block; margin-top: 5px; word-break: break-all;">
                                <?php echo esc_html($emergency_url); ?>
                            </code><br>
                            <small><?php esc_html_e('Save this URL for emergency access if you lose the custom URL.', 'moesec'); ?></small>
                        </p>
                    </div>
                    <?php endif; ?>
                    
                    <?php
                    // Show warning for weak custom URLs
                    if (!empty($custom_admin_url)) {
                        $weak_urls = array('admin', 'login', 'wpadmin', 'wp-admin', 'dashboard', 'secure', 'myadmin', 'administrator');
                        if (in_array($custom_admin_url, $weak_urls) || strlen($custom_admin_url) < 8) {
                            echo '<div style="background: #f8d7da; border-left: 4px solid #dc3545; padding: 10px; margin-top: 10px;">';
                            echo '<strong>' . esc_html__('⚠️ Security Warning:', 'moesec') . '</strong> ';
                            echo esc_html__('Your custom admin URL is too simple or common. Choose a longer, more unique URL for better security.', 'moesec');
                            echo '</div>';
                        }
                    }
                    ?>
                </td>
            </tr>
        </table>
        
        <p class="submit">
            <input type="submit" name="moesec_apply_hardening" class="button button-primary" value="<?php esc_attr_e('Apply Hardening Measures', 'moesec'); ?>">
        </p>
    </form>
    
    <div class="moesec-info-box" style="background: #e7f3ff; border-left: 4px solid #0073aa; padding: 15px; margin: 20px 0;">
        <h4><?php esc_html_e('About Custom Admin URL:', 'moesec'); ?></h4>
        <ul>
            <li><?php esc_html_e('Replaces wp-login.php and wp-admin with your custom URL', 'moesec'); ?></li>
            <li><?php esc_html_e('Protects against automated bot attacks on default WordPress URLs', 'moesec'); ?></li>
            <li><?php esc_html_e('Works with mod_rewrite (Apache) - requires .htaccess', 'moesec'); ?></li>
            <li><?php esc_html_e('Emergency access URL is generated for recovery', 'moesec'); ?></li>
            <li><?php esc_html_e('All access attempts are logged for security monitoring', 'moesec'); ?></li>
            <li><?php esc_html_e('To disable: clear the field and save', 'moesec'); ?></li>
        </ul>
    </div>
    
    <?php if (!empty($custom_admin_url)): ?>
    <div class="moesec-log-box" style="background: #f8f9fa; border: 1px solid #dee2e6; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <h4><?php esc_html_e('Recent Security Logs', 'moesec'); ?></h4>
        <?php moesec_display_security_logs(); ?>
    </div>
    <?php endif; ?>
    <?php
}

function moesec_apply_hardening_measures() {
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to modify security settings.', 'moesec'));
    }
    
    // Disable file editing
    $disable_file_editing = isset($_POST['disable_file_editing']);
    if ($disable_file_editing && !defined('DISALLOW_FILE_EDIT')) {
        $config_file = ABSPATH . 'wp-config.php';
        if (is_writable($config_file)) {
            $config_content = file_get_contents($config_file);
            if (!strpos($config_content, 'DISALLOW_FILE_EDIT')) {
                $config_content = str_replace("<?php", "<?php\ndefine('DISALLOW_FILE_EDIT', true);", $config_content);
                file_put_contents($config_file, $config_content);
            }
        }
    }
    
    update_option('moesec_hide_wp_version', isset($_POST['hide_wp_version']));
    update_option('moesec_disable_xmlrpc', isset($_POST['disable_xmlrpc']));
    update_option('moesec_disable_user_enumeration', isset($_POST['disable_user_enumeration']));
    
    $disable_php_in_uploads = isset($_POST['disable_php_in_uploads']);
    update_option('moesec_disable_php_in_uploads', $disable_php_in_uploads);
    moesec_toggle_php_in_uploads($disable_php_in_uploads);
    
    // Custom admin URL
    $old_custom_admin_url = get_option('moesec_custom_admin_url', '');
    $custom_admin_url = isset($_POST['custom_admin_url']) ? sanitize_title($_POST['custom_admin_url']) : '';
    
    if (!empty($custom_admin_url) && !preg_match('/^[a-z0-9-]+$/', $custom_admin_url)) {
        echo '<div class="error"><p>' . esc_html__('Invalid admin URL format. Use only lowercase letters, numbers, and hyphens.', 'moesec') . '</p></div>';
        return;
    }
    
    $reserved_slugs = array('admin', 'wp-admin', 'wp-login', 'login', 'dashboard', 'wp-content', 'wp-includes', 'feed', 'comments', 'search');
    if (in_array($custom_admin_url, $reserved_slugs)) {
        echo '<div class="error"><p>' . esc_html__('This URL is reserved and cannot be used.', 'moesec') . '</p></div>';
        return;
    }
    
    // Generate new emergency key if custom URL is changing
    if ($custom_admin_url !== $old_custom_admin_url || empty(get_option('moesec_emergency_key'))) {
        update_option('moesec_emergency_key', wp_generate_password(16, false));
    }
    
    update_option('moesec_custom_admin_url', $custom_admin_url);
    
    // Update .htaccess
    $htaccess_updated = moesec_update_htaccess_for_custom_admin($custom_admin_url);
    
    echo '<div class="updated"><p>' . esc_html__('Hardening measures applied successfully.', 'moesec') . '</p></div>';
    
    if (!empty($custom_admin_url)) {
        $emergency_url = home_url('/wp-login.php?moesec_emergency=' . get_option('moesec_emergency_key'));
        echo '<div class="updated"><p><strong>' . 
             sprintf(__('✅ Custom admin URL activated: %s', 'moesec'), '<br><code>' . esc_html(home_url('/' . $custom_admin_url)) . '</code>') . 
             '</strong></p></div>';
        echo '<div class="updated"><p><strong>' . 
             sprintf(__('🔑 Emergency access URL: %s', 'moesec'), '<br><code style="word-break: break-all;">' . esc_html($emergency_url) . '</code>') . 
             '<br><small>' . esc_html__('Save this URL securely for emergency recovery!', 'moesec') . '</small></strong></p></div>';
        
        if (!$htaccess_updated) {
            echo '<div class="error"><p>' . esc_html__('Warning: Could not update .htaccess file. Please check file permissions.', 'moesec') . '</p></div>';
        }
    } else {
        // Clear access cookie when disabling
        setcookie('moesec_admin_access', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
    }
}

// Apply filters
add_action('plugins_loaded', 'moesec_apply_hardening_filters', 1);

function moesec_apply_hardening_filters() {
    if (get_option('moesec_hide_wp_version', false)) {
        add_filter('the_generator', '__return_empty_string');
        remove_action('wp_head', 'wp_generator');
    }
    
    if (get_option('moesec_disable_xmlrpc', false)) {
        add_filter('xmlrpc_enabled', '__return_false');
        add_filter('xmlrpc_methods', '__return_empty_array');
    }
    
    if (get_option('moesec_disable_user_enumeration', false)) {
        if (!is_admin() && isset($_GET['author'])) {
            moesec_log_security_event('user_enumeration_attempt', array(
                'ip' => $_SERVER['REMOTE_ADDR'],
                'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                'author_param' => $_GET['author']
            ));
            wp_die(esc_html__('Forbidden', 'moesec'), 403);
        }
        
        // Block REST API user enumeration
        add_filter('rest_endpoints', function($endpoints) {
            if (isset($endpoints['/wp/v2/users'])) {
                unset($endpoints['/wp/v2/users']);
            }
            if (isset($endpoints['/wp/v2/users/(?P<id>[\d]+)'])) {
                unset($endpoints['/wp/v2/users/(?P<id>[\d]+)']);
            }
            return $endpoints;
        });
    }
    
    // Handle custom admin URL
    $custom_admin_url = get_option('moesec_custom_admin_url', '');
    if (!empty($custom_admin_url)) {
        moesec_enforce_custom_admin_url($custom_admin_url);
    }
}

function moesec_toggle_php_in_uploads($disable) {
    $uploads_dir = wp_upload_dir();
    $htaccess_file = $uploads_dir['basedir'] . '/.htaccess';

    if ($disable) {
        $htaccess_content = "# MoeSec: Disable PHP execution\n";
        $htaccess_content .= "<FilesMatch \"\\.(php|php\\.)$\">\n";
        $htaccess_content .= "Order Allow,Deny\n";
        $htaccess_content .= "Deny from all\n";
        $htaccess_content .= "</FilesMatch>\n";
        file_put_contents($htaccess_file, $htaccess_content);
    } else {
        if (file_exists($htaccess_file)) {
            $current_content = file_get_contents($htaccess_file);
            $new_content = preg_replace('/# MoeSec: Disable PHP execution.*?<\/FilesMatch>\n/s', '', $current_content);
            file_put_contents($htaccess_file, $new_content);
        }
    }
}

// Update .htaccess for custom admin URL - IMPROVED VERSION
function moesec_update_htaccess_for_custom_admin($custom_slug) {
    $htaccess_file = ABSPATH . '.htaccess';
    
    if (!file_exists($htaccess_file) || !is_writable($htaccess_file)) {
        return false;
    }
    
    $htaccess_content = file_get_contents($htaccess_file);
    
    // Remove old rules
    $htaccess_content = preg_replace('/# BEGIN MoeSec Custom Admin.*?# END MoeSec Custom Admin\n*/s', '', $htaccess_content);
    
    if (!empty($custom_slug)) {
        $home_path = parse_url(home_url(), PHP_URL_PATH);
        $home_path = $home_path ? rtrim($home_path, '/') : '';
        
        $rules = "# BEGIN MoeSec Custom Admin\n";
        $rules .= "<IfModule mod_rewrite.c>\n";
        $rules .= "RewriteEngine On\n";
        $rules .= "RewriteBase " . ($home_path ? $home_path . '/' : '/') . "\n";
        $rules .= "# Redirect custom admin URL to wp-login.php\n";
        $rules .= "RewriteRule ^" . preg_quote($custom_slug, '/') . "/?$ " . $home_path . "/wp-login.php [L,QSA]\n";
        $rules .= "RewriteRule ^" . preg_quote($custom_slug, '/') . "/(.*)$ " . $home_path . "/wp-admin/$1 [L,QSA]\n";
        $rules .= "# Block direct access to wp-login.php (except emergency access)\n";
        $rules .= "RewriteCond %{ENV:REDIRECT_STATUS} ^\$\n";
        $rules .= "RewriteCond %{QUERY_STRING} !moesec_emergency=[a-zA-Z0-9]{16} [NC]\n";
        $rules .= "RewriteCond %{REQUEST_URI} ^" . $home_path . "/wp-login\\.php [NC]\n";
        $rules .= "RewriteCond %{HTTP_COOKIE} !moesec_admin_access [NC]\n";
        $rules .= "RewriteRule ^wp-login\\.php$ - [R=403,L]\n";
        $rules .= "# Block direct access to wp-admin (except emergency access)\n";
        $rules .= "RewriteCond %{ENV:REDIRECT_STATUS} ^\$\n";
        $rules .= "RewriteCond %{QUERY_STRING} !moesec_emergency=[a-zA-Z0-9]{16} [NC]\n";
        $rules .= "RewriteCond %{REQUEST_URI} ^" . $home_path . "/wp-admin/? [NC]\n";
        $rules .= "RewriteCond %{HTTP_COOKIE} !moesec_admin_access [NC]\n";
        $rules .= "RewriteRule ^wp-admin/?(.*)$ - [R=403,L]\n";
        $rules .= "</IfModule>\n";
        $rules .= "# END MoeSec Custom Admin\n\n";
        
        if (strpos($htaccess_content, '# BEGIN WordPress') !== false) {
            $htaccess_content = str_replace('# BEGIN WordPress', $rules . '# BEGIN WordPress', $htaccess_content);
        } else {
            $htaccess_content = $rules . $htaccess_content;
        }
    }
    
    return file_put_contents($htaccess_file, $htaccess_content) !== false;
}

// Enforce custom admin URL
function moesec_enforce_custom_admin_url($custom_slug) {
    // Skip for AJAX, CRON, REST, and admin-ajax.php
    if (defined('DOING_AJAX') || defined('DOING_CRON') || defined('REST_REQUEST') || 
        (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === 'admin-ajax.php')) {
        return;
    }
    
    $request_uri = $_SERVER['REQUEST_URI'];
    $script_name = isset($_SERVER['SCRIPT_NAME']) ? basename($_SERVER['SCRIPT_NAME']) : '';
    
    // Check for emergency access
    $emergency_key = get_option('moesec_emergency_key', '');
    if (isset($_GET['moesec_emergency']) && $_GET['moesec_emergency'] === $emergency_key) {
        // Set emergency access cookie (valid for 1 hour)
        setcookie('moesec_admin_access', wp_hash($custom_slug . '_emergency'), time() + 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
        $_COOKIE['moesec_admin_access'] = wp_hash($custom_slug . '_emergency');
        
        moesec_log_security_event('emergency_access_used', array(
            'ip' => $_SERVER['REMOTE_ADDR'],
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            'timestamp' => time()
        ));
        
        return;
    }
    
    // Check if this is the custom admin URL
    $is_custom_admin = (strpos($request_uri, '/' . $custom_slug) === 0);
    
    // Check if this is default admin access
    $is_default_admin = ($script_name === 'wp-login.php' || strpos($request_uri, '/wp-admin') === 0);
    
    // If accessing custom admin URL, set access cookie and allow
    if ($is_custom_admin) {
        // Set cookie to allow admin access (valid for 1 day)
        if (!isset($_COOKIE['moesec_admin_access']) || $_COOKIE['moesec_admin_access'] !== wp_hash($custom_slug)) {
            setcookie('moesec_admin_access', wp_hash($custom_slug), time() + 86400, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
            $_COOKIE['moesec_admin_access'] = wp_hash($custom_slug);
        }
        return;
    }
    
    // If accessing default admin URLs, block unless authorized
    if ($is_default_admin) {
        $has_valid_access = false;
        
        // Allow if user is logged in as admin
        if (is_user_logged_in() && current_user_can('manage_options')) {
            $has_valid_access = true;
        }
        // Allow if has valid access cookie (normal or emergency)
        elseif (isset($_COOKIE['moesec_admin_access']) && 
               ($_COOKIE['moesec_admin_access'] === wp_hash($custom_slug) || 
                $_COOKIE['moesec_admin_access'] === wp_hash($custom_slug . '_emergency'))) {
            $has_valid_access = true;
        }
        
        // Block unauthorized access to default admin URLs
        if (!$has_valid_access) {
            // Log the blocked attempt
            moesec_log_security_event('admin_access_blocked', array(
                'ip' => $_SERVER['REMOTE_ADDR'],
                'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                'request_uri' => $request_uri,
                'script_name' => $script_name,
                'timestamp' => time()
            ));
            
            // If trying to access wp-login.php, redirect to custom URL
            if ($script_name === 'wp-login.php' && !is_user_logged_in()) {
                wp_redirect(home_url('/' . $custom_slug));
                exit;
            }
            
            // For other admin pages, show access denied
            wp_die(
                '<h1>' . esc_html__('Access Denied', 'moesec') . '</h1>' .
                '<p>' . sprintf(esc_html__('Website Protected by MoeSec.com WordPress Security Plugin', 'moesec'), 
                    '<strong><a href="' . esc_url(home_url('/' . $custom_slug)) . '">' . 
                    esc_html(home_url('/' . $custom_slug)) . '</a></strong>') . '</p>' .
                '<p><small>' . esc_html__('All access attempts are logged for security monitoring.', 'moesec') . '</small></p>',
                esc_html__('Access Denied', 'moesec'),
                array('response' => 403)
            );
        }
    }
}

// Security logging system
function moesec_log_security_event($event_type, $data = array()) {
    $logs = get_option('moesec_security_logs', array());
    
    $log_entry = array(
        'timestamp' => time(),
        'type' => $event_type,
        'ip' => $data['ip'] ?? $_SERVER['REMOTE_ADDR'],
        'user_agent' => $data['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'),
        'data' => $data
    );
    
    // Add to beginning of array (newest first)
    array_unshift($logs, $log_entry);
    
    // Keep only last 100 logs
    if (count($logs) > 100) {
        $logs = array_slice($logs, 0, 100);
    }
    
    update_option('moesec_security_logs', $logs);
}

// Display security logs
function moesec_display_security_logs() {
    $logs = get_option('moesec_security_logs', array());
    
    if (empty($logs)) {
        echo '<p>' . esc_html__('No security events logged yet.', 'moesec') . '</p>';
        return;
    }
    
    echo '<table class="widefat" style="font-size: 12px;">';
    echo '<thead><tr>
        <th>' . esc_html__('Time', 'moesec') . '</th>
        <th>' . esc_html__('Event', 'moesec') . '</th>
        <th>' . esc_html__('IP Address', 'moesec') . '</th>
        <th>' . esc_html__('Details', 'moesec') . '</th>
    </tr></thead>';
    echo '<tbody>';
    
    foreach (array_slice($logs, 0, 20) as $log) { // Show last 20 logs
        $time = date('Y-m-d H:i:s', $log['timestamp']);
        $ip = esc_html($log['ip']);
        $event_type = esc_html($log['type']);
        
        // Human readable event types
        $event_labels = array(
            'admin_access_blocked' => __('Admin Access Blocked', 'moesec'),
            'emergency_access_used' => __('Emergency Access Used', 'moesec'),
            'user_enumeration_attempt' => __('User Enumeration Attempt', 'moesec')
        );
        
        $event_label = $event_labels[$event_type] ?? $event_type;
        
        // Event-specific details
        $details = '';
        switch ($event_type) {
            case 'admin_access_blocked':
                $details = esc_html__('Attempt to access default admin URLs', 'moesec');
                break;
            case 'emergency_access_used':
                $details = esc_html__('Emergency access key was used', 'moesec');
                break;
            case 'user_enumeration_attempt':
                $author_param = $log['data']['author_param'] ?? 'unknown';
                $details = sprintf(esc_html__('Author parameter: %s', 'moesec'), esc_html($author_param));
                break;
            default:
                $details = esc_html__('Security event detected', 'moesec');
        }
        
        echo '<tr>';
        echo '<td>' . esc_html($time) . '</td>';
        echo '<td><span style="color: #d63638;">⚠️ ' . esc_html($event_label) . '</span></td>';
        echo '<td><code>' . esc_html($ip) . '</code></td>';
        echo '<td>' . esc_html($details) . '</td>';
        echo '</tr>';
    }
    
    echo '</tbody></table>';
    
    if (count($logs) > 20) {
        echo '<p style="text-align: center; margin-top: 10px;">';
        echo sprintf(esc_html__('Showing last 20 of %d logged events', 'moesec'), count($logs));
        echo '</p>';
    }
    
    // Clear logs button
    echo '<form method="post" style="margin-top: 15px;">';
    wp_nonce_field('moesec_clear_logs', 'moesec_clear_logs_nonce');
    echo '<input type="hidden" name="moesec_clear_logs" value="1">';
    echo '<input type="submit" class="button" value="' . esc_attr__('Clear Logs', 'moesec') . '">';
    echo '</form>';
}

// Handle log clearing
add_action('admin_init', function() {
    if (isset($_POST['moesec_clear_logs']) && check_admin_referer('moesec_clear_logs', 'moesec_clear_logs_nonce')) {
        if (current_user_can('manage_options')) {
            update_option('moesec_security_logs', array());
            echo '<div class="updated"><p>' . esc_html__('Security logs cleared.', 'moesec') . '</p></div>';
        }
    }
});

// Emergency access cleanup on deactivation
register_deactivation_hook(__FILE__, 'moesec_cleanup_custom_admin');

function moesec_cleanup_custom_admin() {
    $custom_admin_url = get_option('moesec_custom_admin_url', '');
    if (!empty($custom_admin_url)) {
        // Clear the access cookie
        setcookie('moesec_admin_access', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
        // Remove .htaccess rules
        moesec_update_htaccess_for_custom_admin('');
    }
}
