<?php
/**
 * File Guard for BotFend Anti-Bot Firewall - REFACTORED
 * 
 * Handles file system protection, uploads security, and file integrity monitoring.
 * File operations are handled directly; database operations delegated to Core.
 *
 * @package BotFend\Security
 * @version 4.8.4 - Removed plugin updater detection methods for WordPress.org compliance
 */

namespace BotFend\Security;

use BotFend\Core\Config;
use BotFend\Core\Core;
use BotFend\Logging\Logger;

defined('ABSPATH') || exit;

/**
 * Class FileGuard
 *
 * Enterprise-grade file system protection with multi-layer security
 * - File system operations (allowed)
 * - Database operations via Core only
 */
class FileGuard {

    private $config;
    private $core;
    private $logger;
    private $server_software;
    private $wp_filesystem;

    const NOTICE_PREFIX = 'botfend_dismissed_';

    const BLOCKED_EXTENSIONS = [
        'php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'php8',
        'phps', 'pht', 'phtm', 'pgif', 'pjpeg', 'pjpg',
        'htaccess', 'htpasswd', 'ini', 'log', 'sql'
    ];

    const CRITICAL_PERMISSIONS = [
        'wp-config.php' => 0644,
        '.htaccess' => 0644,
        'index.php' => 0644,
        'wp-load.php' => 0644,
        'wp-blog-header.php' => 0644,
    ];

    const BOTFEND_START_MARKER = '# BotFend Anti-Bot Firewall Multi-Layer Protection';
    const BOTFEND_END_MARKER = '# End BotFend Anti-Bot Firewall';

    /**
     * Constructor
     *
     * @param Logger $logger Logger instance
     * @param Core   $core   Core instance (for logging and blocking)
     */
    public function __construct(Logger $logger, Core $core) {
        $this->config = Config::get_instance();
        $this->logger = $logger;
        $this->core = $core;
        $this->server_software = $this->get_server_software();
        
        $this->init_filesystem();
        $this->init_hooks();
    }

    /**
     * WP_Filesystem initialization
     */
    private function init_filesystem() {
        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        
        if (get_filesystem_method() === 'direct') {
            WP_Filesystem();
            global $wp_filesystem;
            $this->wp_filesystem = $wp_filesystem;
            return true;
        }
        
        $this->logger->debug('WP_Filesystem direct access not available, using native PHP file operations', ['source' => 'file_guard']);
        return false;
    }

    private function safe_put_contents($file_path, $content, $mode = false) {
        if (file_exists($file_path)) {
            $backup = $file_path . '.botfend-backup';
            
            $copied = false;
            if ($this->wp_filesystem instanceof \WP_Filesystem_Base) {
                $copied = $this->wp_filesystem->copy($file_path, $backup, true);
            } else {
                $copied = copy($file_path, $backup);
            }

            if (!$copied) {
                $this->logger->warning('Failed to create backup before writing', [
                    'source' => 'file_guard',
                    'file' => $file_path
                ]);
            }
        }
        
        if ($this->wp_filesystem instanceof \WP_Filesystem_Base) {
            $result = $this->wp_filesystem->put_contents($file_path, $content, $mode);
        } else {
            $result = file_put_contents($file_path, $content);
            if ($result !== false && $mode) {
                wp_chmod($file_path, $mode);
            }
            $result = ($result !== false);
        }
        
        if ($result) {
            $this->logger->info('File written successfully', [
                'source' => 'file_guard',
                'file' => $file_path
            ]);
        } else {
            $this->logger->error('Failed to write file', [
                'source' => 'file_guard',
                'file' => $file_path
            ]);
        }
        
        return $result;
    }

    private function get_server_software() {
        if (!isset($_SERVER['SERVER_SOFTWARE'])) {
            return 'Unknown';
        }
        return sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE']));
    }

    private function init_hooks() {
        add_action('init', [$this, 'secure_uploads_directory'], 1);
        add_action('init', [$this, 'disable_file_editors'], 1);
        add_action('admin_init', [$this, 'block_editor_file_access'], 1);
        
        add_filter('user_has_cap', [$this, 'restrict_plugin_capabilities'], 10, 4);
        add_filter('plugin_action_links', [$this, 'filter_plugin_actions'], 10, 4);
        add_filter('plugin_install_action_links', [$this, 'filter_plugin_install_actions'], 10, 2);
        add_filter('theme_action_links', [$this, 'filter_theme_actions'], 10, 2);
        add_filter('all_plugins', [$this, 'filter_plugin_list']);
        
        add_filter('wp_handle_upload', [$this, 'inspect_uploaded_file'], 10, 2);
        add_filter('wp_handle_sideload', [$this, 'inspect_uploaded_file'], 10, 2);
        
        add_action('init', [$this, 'schedule_cron_jobs']);
        add_action('botfend_file_guard_weekly', [$this, 'run_weekly_maintenance']);
        add_action('botfend_file_guard_daily', [$this, 'run_daily_maintenance']);
        
        add_action('upgrader_process_complete', [$this, 'after_update'], 10, 2);
        add_action('admin_notices', [$this, 'show_file_warnings']);
        
        add_action('wp_ajax_botfend_dismiss_notice', [$this, 'handle_notice_dismissal']);
        add_action('wp_ajax_botfend_protect_uploads', [$this, 'ajax_protect_uploads']);
        add_action('wp_ajax_botfend_check_permissions', [$this, 'ajax_check_permissions']);
        
        add_action('template_redirect', [$this, 'block_direct_php_access']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    }

    public function schedule_cron_jobs() {
        if (!wp_next_scheduled('botfend_file_guard_weekly')) {
            wp_schedule_event(time(), 'weekly', 'botfend_file_guard_weekly');
        }
        
        if (!wp_next_scheduled('botfend_file_guard_daily')) {
            wp_schedule_event(time(), 'daily', 'botfend_file_guard_daily');
        }
    }

    public function enqueue_admin_assets($hook) {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        if (strpos($hook, 'botfend-') === false) {
            return;
        }
        
        wp_enqueue_script(
            'botfend-file-guard',
            BOTFEND_ASSETS_URL . 'js/admin-file-guard.js',
            ['jquery'],
            BOTFEND_VERSION,
            true
        );
        
        wp_localize_script('botfend-file-guard', 'botfendFileGuard', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('botfend_file_guard'),
            'strings' => [
                'applying' => __('Applying...', 'botfend-anti-bot-firewall'),
                'success' => __('Protection applied successfully!', 'botfend-anti-bot-firewall'),
                'error' => __('Error applying protection. Please try again.', 'botfend-anti-bot-firewall'),
                'confirm' => __('Are you sure?', 'botfend-anti-bot-firewall')
            ]
        ]);
        
        wp_enqueue_style(
            'botfend-file-guard',
            BOTFEND_ASSETS_URL . 'css/admin-file-guard.css',
            [],
            BOTFEND_VERSION
        );
    }

    public function filter_plugin_list($all_plugins) {
        return $all_plugins;
    }

    public function secure_uploads_directory() {
        if (!$this->config->get_bool('protect_uploads', false)) {
            return;
        }
        
        $last_check = get_transient('botfend_uploads_secured');
        if ($last_check && !defined('WP_DEBUG')) {
            return;
        }
        
        $upload_dir = wp_get_upload_dir();
        
        if (!is_dir($upload_dir['basedir'])) {
            $this->logger->warning('Uploads directory not found', ['source' => 'file_guard']);
            return;
        }

        if (!is_writable($upload_dir['basedir'])) {
            $this->logger->warning('Uploads directory not writable', ['source' => 'file_guard']);
            return;
        }

        $blocked = $this->get_blocked_extensions();

        $results = [
            'htaccess' => $this->create_htaccess_protection($upload_dir, $blocked),
            'web_config' => $this->create_webconfig_protection($upload_dir, $blocked),
            'php_fallback' => $this->create_php_fallback($upload_dir, $blocked),
            'index' => $this->create_index_file($upload_dir)
        ];

        $success = !in_array(false, $results, true);

        if ($success) {
            set_transient('botfend_uploads_secured', true, DAY_IN_SECONDS);
            $this->logger->info('Uploads directory secured successfully', [
                'source' => 'file_guard',
                'methods' => array_keys(array_filter($results))
            ]);
        } else {
            $this->logger->error('Failed to fully secure uploads directory', [
                'source' => 'file_guard',
                'results' => $results
            ]);
        }
    }

    private function get_blocked_extensions() {
        $extensions = $this->config->get_array(
            'blocked_upload_extensions',
            self::BLOCKED_EXTENSIONS
        );
        
        $critical = ['php', 'phtml', 'htaccess', 'htpasswd'];
        return array_unique(array_merge($critical, $extensions));
    }

    private function create_htaccess_protection($upload_dir, $extensions) {
        $file = $upload_dir['basedir'] . '/.htaccess';
        
        $pattern = implode('|', array_map('preg_quote', $extensions));
        
        $rules = self::BOTFEND_START_MARKER . "\n";
        $rules .= "# Created: " . current_time('mysql') . "\n";
        $rules .= "# Blocks PHP execution in uploads directory\n\n";
        
        $rules .= "<IfModule mod_authz_core.c>\n";
        $rules .= "    <FilesMatch \"\.({$pattern})$\">\n";
        $rules .= "        Require all denied\n";
        $rules .= "    </FilesMatch>\n";
        $rules .= "</IfModule>\n\n";
        
        $rules .= "<IfModule !mod_authz_core.c>\n";
        $rules .= "    <FilesMatch \"\.({$pattern})$\">\n";
        $rules .= "        Order deny,allow\n";
        $rules .= "        Deny from all\n";
        $rules .= "    </FilesMatch>\n";
        $rules .= "</IfModule>\n\n";
        
        $rules .= "<IfModule LiteSpeed>\n";
        $rules .= "    php_flag engine off\n";
        $rules .= "</IfModule>\n\n";
        
        $rules .= "<Files ~ \"^\.ht\">\n";
        $rules .= "    Require all denied\n";
        $rules .= "</Files>\n";
        
        $rules .= self::BOTFEND_END_MARKER . "\n";
        
        if (file_exists($file)) {
            $existing = file_get_contents($file);
            
            $pattern_replace = '/' . preg_quote(self::BOTFEND_START_MARKER, '/') . '.*?' . preg_quote(self::BOTFEND_END_MARKER, '/') . '/s';
            $existing = preg_replace($pattern_replace, '', $existing);
            $existing = trim($existing);
            
            if (!empty($existing)) {
                $rules = $existing . "\n\n" . $rules;
            }
        }
        
        return $this->safe_put_contents($file, $rules, FS_CHMOD_FILE);
    }

    private function create_webconfig_protection($upload_dir, $extensions) {
        $file = $upload_dir['basedir'] . '/web.config';
        
        if (stripos($this->server_software, 'microsoft-iis') === false && 
            stripos($this->server_software, 'iis') === false) {
            return true;
        }
        
        $file_extensions_xml = '';
        foreach ($extensions as $ext) {
            $file_extensions_xml .= "                <add fileExtension=\".{$ext}\" allowed=\"false\" />\n";
        }
        
        $web_config = '<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <security>
            <requestFiltering>
                <fileExtensions allowUnlisted="true">
' . $file_extensions_xml . '                </fileExtensions>
                <hiddenSegments>
                    <add segment="web.config" />
                </hiddenSegments>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>';
        
        return $this->safe_put_contents($file, $web_config, FS_CHMOD_FILE);
    }

    private function create_php_fallback($upload_dir, $extensions) {
        $file = $upload_dir['basedir'] . '/index.php';
        
        $pattern = implode('|', $extensions);
        
        $content = "<?php
/**
 * BotFend Anti-Bot Firewall PHP Fallback Protection
 * Works on ALL servers
 */

// Block direct access to executable files
if (preg_match('/\\\\.({$pattern})$/i', \$_SERVER['REQUEST_URI'] ?? '')) {
    status_header(403);
    header('Content-Type: text/plain');
    die('Access Denied - File execution blocked');
}

// Block directory listing attempts
if ((isset(\$_SERVER['REQUEST_URI']) && substr(\$_SERVER['REQUEST_URI'], -1) === '/') && 
    (!isset(\$_SERVER['QUERY_STRING']) || empty(\$_SERVER['QUERY_STRING']))) {
    status_header(403);
    die('Directory listing is not allowed');
}

// Normal request - serve through WordPress
?>";
        
        return $this->safe_put_contents($file, $content, FS_CHMOD_FILE);
    }

    private function create_index_file($upload_dir) {
        $file = $upload_dir['basedir'] . '/index.php';
        
        if (file_exists($file) && filesize($file) > 100) {
            return true;
        }
        
        $content = "<?php\n// BotFend Anti-Bot Firewall - Directory listing blocked\n?>";
        
        return $this->safe_put_contents($file, $content, FS_CHMOD_FILE);
    }

    public function block_direct_php_access() {
        if (!$this->config->get_bool('protect_uploads', false)) {
            return;
        }
        
        $request_uri = isset($_SERVER['REQUEST_URI']) 
            ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']))
            : '';
            
        if (empty($request_uri)) {
            return;
        }
        
        $upload_dir = wp_get_upload_dir();
        $upload_url = $upload_dir['baseurl'];
        $upload_path = wp_parse_url($upload_url, PHP_URL_PATH);
        
        if (strpos($request_uri, $upload_path) === false) {
            return;
        }
        
        $ext = strtolower(pathinfo($request_uri, PATHINFO_EXTENSION));
        $blocked = $this->get_blocked_extensions();
        
        if (in_array($ext, $blocked, true)) {
            status_header(403);
            wp_die(
                esc_html__('Access Denied - File execution blocked by BotFend Anti-Bot Firewall', 'botfend-anti-bot-firewall'),
                esc_html__('Access Denied', 'botfend-anti-bot-firewall'),
                ['response' => 403]
            );
        }
    }

    public function disable_file_editors() {
        if (!$this->config->get_bool('disable_file_editors', false)) {
            return;
        }
        
        add_filter('user_has_cap', [$this, 'restrict_editor_capabilities'], 10, 4);
        add_action('admin_menu', [$this, 'hide_editor_menus'], 999);
        add_action('admin_bar_menu', [$this, 'hide_editor_admin_bar_links'], 999);
        
        // REMOVED: Plugin updater detection methods (not permitted on WordPress.org)
        // The disable_file_mods setting is handled by restrict_plugin_capabilities only
    }

    public function restrict_editor_capabilities($allcaps, $caps, $args, $user) {
        if (!$this->config->get_bool('disable_file_editors', false)) {
            return $allcaps;
        }
        
        $restricted_caps = [
            'edit_themes',
            'edit_plugins',
            'edit_theme_options', 
        ];
        
        foreach ($restricted_caps as $cap) {
            if (isset($allcaps[$cap])) {
                $allcaps[$cap] = false;
            }
        }
        
        return $allcaps;
    }

    public function hide_editor_menus() {
        if (!$this->config->get_bool('disable_file_editors', false)) {
            return;
        }
        
        remove_submenu_page('themes.php', 'theme-editor.php');
        remove_submenu_page('plugins.php', 'plugin-editor.php');
        
        global $submenu;
        
        if (isset($submenu['themes.php'])) {
            foreach ($submenu['themes.php'] as $key => $item) {
                if (isset($item[2]) && $item[2] === 'theme-editor.php') {
                    unset($submenu['themes.php'][$key]);
                    break;
                }
            }
        }
        
        if (isset($submenu['plugins.php'])) {
            foreach ($submenu['plugins.php'] as $key => $item) {
                if (isset($item[2]) && $item[2] === 'plugin-editor.php') {
                    unset($submenu['plugins.php'][$key]);
                    break;
                }
            }
        }
        
        remove_menu_page('theme-editor.php');
        remove_menu_page('plugin-editor.php');
    }

    public function hide_editor_admin_bar_links($wp_admin_bar) {
        if (!$this->config->get_bool('disable_file_editors', false)) {
            return;
        }
        
        $wp_admin_bar->remove_node('theme-editor');
        $wp_admin_bar->remove_node('plugin-editor');
    }

    public function filter_theme_actions($actions, $theme) {
        if (!$this->config->get_bool('disable_file_editors', false)) {
            return $actions;
        }
        
        if (isset($actions['edit'])) {
            $actions['edit'] = '<span style="opacity:0.5; pointer-events:none; color:#999;" title="' . 
                esc_attr__('Theme editing disabled by BotFend Anti-Bot Firewall', 'botfend-anti-bot-firewall') . '">' .
                esc_html__('Edit (Disabled)', 'botfend-anti-bot-firewall') . '</span>';
        }
        
        return $actions;
    }
    
    public function block_editor_file_access() {
        if (!$this->config->get_bool('disable_file_editors', false)) {
            return;
        }
        
        $current_url = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '';
        
        if (strpos($current_url, 'theme-editor.php') !== false || 
            strpos($current_url, 'plugin-editor.php') !== false) {
            
            $settings_url = admin_url('admin.php?page=botfend-settings&tab=file_guard');
            
            $message = sprintf(
                '<p>%s</p><p><a href="%s">%s</a></p>',
                esc_html__('The Theme and Plugin editors have been disabled by BotFend Anti-Bot Firewall to prevent malicious code injection.', 'botfend-anti-bot-firewall'),
                esc_url($settings_url),
                esc_html__('Manage File Guard Settings', 'botfend-anti-bot-firewall')
            );

            wp_die(
                $message,
                esc_html__('Editor Access Blocked', 'botfend-anti-bot-firewall'),
                ['response' => 403, 'back_link' => true]
            );
        }
    }

    // REMOVED: disable_update_capabilities() method - not permitted on WordPress.org
    // REMOVED: remove_update_notifications() method - not permitted on WordPress.org
    // REMOVED: remove_install_tabs() method - not permitted on WordPress.org

    public function restrict_plugin_capabilities($allcaps, $caps, $args, $user) {
        if (!$this->config->get_bool('disable_file_mods', false)) {
            return $allcaps;
        }
        
        $restricted_caps = [
            'install_plugins', 'delete_plugins', 'update_plugins', 'update_plugins_network',
            'install_themes', 'delete_themes', 'update_themes', 'update_themes_network',
            'update_core', 'install_languages', 'update_languages',
            'delete_site', 'upgrade_network', 'setup_network'
        ];
        
        foreach ($restricted_caps as $cap) {
            if (isset($allcaps[$cap])) {
                $allcaps[$cap] = false;
            }
        }
        
        return $allcaps;
    }

    public function filter_plugin_actions($actions, $plugin_file, $plugin_data, $context) {
        if ($this->config->get_bool('disable_file_mods', false)) {
            if (isset($actions['deactivate'])) {
                $actions['deactivate'] = '<span style="opacity:0.5; pointer-events:none; color:#999;" title="' . esc_attr__('Deactivation disabled by BotFend', 'botfend-anti-bot-firewall') . '">' . esc_html__('Deactivate (Disabled)', 'botfend-anti-bot-firewall') . '</span>';
            }
            if (isset($actions['activate'])) {
                $actions['activate'] = '<span style="opacity:0.5; pointer-events:none; color:#999;" title="' . esc_attr__('Activation disabled by BotFend', 'botfend-anti-bot-firewall') . '">' . esc_html__('Activate (Disabled)', 'botfend-anti-bot-firewall') . '</span>';
            }
            if (isset($actions['delete'])) {
                $actions['delete'] = '<span style="opacity:0.5; pointer-events:none; color:#999;" title="' . esc_attr__('Deletion disabled by BotFend', 'botfend-anti-bot-firewall') . '">' . esc_html__('Delete (Disabled)', 'botfend-anti-bot-firewall') . '</span>';
            }
            if (isset($actions['edit'])) {
                $actions['edit'] = '<span style="opacity:0.5; pointer-events:none; color:#999;" title="' . esc_attr__('Editing disabled by BotFend', 'botfend-anti-bot-firewall') . '">' . esc_html__('Edit (Disabled)', 'botfend-anti-bot-firewall') . '</span>';
            }
        }
        
        return $actions;
    }

    public function filter_plugin_install_actions($action_links, $api) {
        if ($this->config->get_bool('disable_file_mods', false)) {
            return ['<span style="color:#999;">' . esc_html__('Installation disabled by BotFend', 'botfend-anti-bot-firewall') . '</span>'];
        }
        
        return $action_links;
    }

    public function inspect_uploaded_file($upload, $context) {
        if (!$this->config->get_bool('scan_uploads', false)) {
            return $upload;
        }
        
        if (!isset($upload['file']) || !file_exists($upload['file'])) {
            return $upload;
        }
        
        $result = $this->scan_file($upload['file']);
        
        if ($result['threat_detected']) {
            // Log through Core
            $ip = $this->get_client_ip();
            $this->core->log_threat($ip, 9, ['Malicious file upload blocked: ' . $result['reason']], 'file_guard');
            
            // Optionally block IP if repeat offender
            $this->core->maybe_block($ip, 9, 'Malicious file upload attempt', 'file_guard');
            
            wp_delete_file($upload['file']);
            
            $upload['error'] = sprintf(
                esc_html__('File blocked by BotFend Anti-Bot Firewall: %s', 'botfend-anti-bot-firewall'),
                $result['reason']
            );
        }
        
        return $upload;
    }

    private function scan_file($file_path) {
        $result = [
            'threat_detected' => false,
            'reason' => ''
        ];
        
        $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
        $blocked = $this->get_blocked_extensions();
        
        if (in_array($ext, $blocked, true)) {
            $result['threat_detected'] = true;
            $result['reason'] = 'File extension is strictly blocked for uploads';
            return $result;
        }
        
        if (filesize($file_path) > 5 * 1024 * 1024) {
            return $result; 
        }
        
        $content = file_get_contents($file_path);
        if ($content === false) {
            return $result;
        }
        
        $patterns = [
            'eval\s*\(' => 'eval() usage detected',
            'base64_decode\s*\(' => 'base64_decode usage',
            'system\s*\(' => 'system() usage',
            'exec\s*\(' => 'exec() usage',
            'shell_exec\s*\(' => 'shell_exec() usage',
            'passthru\s*\(' => 'passthru() usage',
            'popen\s*\(' => 'popen() usage',
            'proc_open\s*\(' => 'proc_open() usage',
            'pcntl_exec' => 'pcntl_exec usage',
            'gzinflate\s*\(' => 'obfuscated code',
            'gzuncompress\s*\(' => 'obfuscated code',
            'str_rot13\s*\(' => 'obfuscated code',
            'preg_replace\s*\(\s*(["\'])//e' => 'dangerous preg_replace'
        ];
        
        foreach ($patterns as $pattern => $reason) {
            if (preg_match('/' . $pattern . '/i', $content)) {
                $result['threat_detected'] = true;
                $result['reason'] = $reason;
                break;
            }
        }
        
        return $result;
    }

    public function check_file_permissions() {
        if (!$this->config->get_bool('monitor_permissions', false)) {
            return [];
        }
        
        $files = $this->get_critical_files();
        $issues = [];
        $auto_fix = $this->config->get_bool('auto_fix_permissions', false);
        
        foreach ($files as $path => $recommended) {
            if (!file_exists($path)) {
                continue;
            }
            
            $perms = fileperms($path);
            $current = $perms & 0777;
            
            if ($current > $recommended) {
                $is_dir = is_dir($path);
                $type_str = $is_dir ? __('Directory', 'botfend-anti-bot-firewall') : __('File', 'botfend-anti-bot-firewall');
                
                $issue = [
                    'file' => $path,
                    'current_permission' => sprintf('%04o', $current),
                    'expected_permission' => sprintf('%04o', $recommended),
                    'reason' => sprintf(__('%s permissions are too loose and should be restricted.', 'botfend-anti-bot-firewall'), $type_str),
                    'fixed' => false
                ];
                
                if ($auto_fix) {
                    $fixed = false;
                    
                    // Attempt native PHP chmod first
                    if (@chmod($path, $recommended)) {
                        $fixed = true;
                    } 
                    // Fallback to WP_Filesystem if native fails
                    elseif ($this->wp_filesystem instanceof \WP_Filesystem_Base) {
                        $fixed = $this->wp_filesystem->chmod($path, $recommended);
                    }
                    
                    if ($fixed) {
                        $issue['fixed'] = true;
                        $issue['current_permission'] = sprintf('%04o', $recommended);
                        $this->logger->info('Fixed file permissions', [
                            'source' => 'file_guard',
                            'file' => $path
                        ]);
                    } else {
                        $issue['reason'] .= ' ' . __('(Auto-fix failed: Your web host restricts PHP from changing permissions. Please change via FTP).', 'botfend-anti-bot-firewall');
                    }
                }
                
                $issues[] = $issue;
            }
        }
        
        // Count ONLY unfixed issues for the alert notification
        $unfixed_count = 0;
        foreach ($issues as $issue) {
            if (!$issue['fixed']) {
                $unfixed_count++;
            }
        }
        
        if ($unfixed_count > 0) {
            update_option('botfend_permission_issues', [
                'count' => $unfixed_count,
                'issues' => $issues,
                'time' => time()
            ]);
        } else {
            delete_option('botfend_permission_issues');
        }
        
        return $issues;
    }
    

    private function get_critical_files() {
        $upload_dir = wp_get_upload_dir();
        
        $files = [
            ABSPATH . 'wp-config.php' => 0644,
            ABSPATH . '.htaccess' => 0644,
            ABSPATH . 'index.php' => 0644,
            ABSPATH . 'wp-load.php' => 0644,
            ABSPATH . 'wp-blog-header.php' => 0644,
            WP_CONTENT_DIR . '/index.php' => 0644,
            WP_PLUGIN_DIR => 0755,
            WP_CONTENT_DIR . '/themes' => 0755,
            $upload_dir['basedir'] => 0755
        ];
        
        $htaccess = $upload_dir['basedir'] . '/.htaccess';
        if (file_exists($htaccess)) {
            $files[$htaccess] = 0644;
        }
        
        return $files;
    }

    public function verify_uploads_protection() {
        if (!$this->config->get_bool('protect_uploads', false)) {
            return;
        }
        
        $upload_dir = wp_get_upload_dir();
        $php_fallback = $upload_dir['basedir'] . '/index.php';
        
        if (!file_exists($php_fallback)) {
            $this->secure_uploads_directory();
            $this->logger->warning('Uploads protection restored - file missing', ['source' => 'file_guard']);
            return;
        }
        
        $content = file_get_contents($php_fallback);
        if (strpos($content, 'BotFend Anti-Bot Firewall') === false) {
            $this->secure_uploads_directory();
            $this->logger->warning('Uploads protection restored - file modified', ['source' => 'file_guard']);
        }
    }

    public function run_weekly_maintenance() {
        $this->verify_uploads_protection();
        $this->cleanup_old_logs();
    }

    public function run_daily_maintenance() {
        $this->check_file_permissions();
    }

    private function cleanup_old_logs() {
        global $wpdb;
        
        $cutoff = gmdate('Y-m-d H:i:s', strtotime('-30 days'));
        
        // Use Core's database for cleanup (read operation)
        $db = $this->core->get_database();
        if (method_exists($db, 'perform_maintenance')) {
            $db->perform_maintenance();
            return;
        }
        
        // Fallback: direct query (read only)
        $table = $wpdb->prefix . 'botfend_logs';
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($table)));
        
        if ($table_exists === $table) {
            $wpdb->query($wpdb->prepare(
                "DELETE FROM `{$table}` WHERE source = %s AND created_at < %s",
                'file_guard',
                $cutoff
            ));
        }
    }

    public function after_update($upgrader, $options) {
        if ($options['type'] === 'core') {
            $this->secure_uploads_directory();
            $this->logger->info('Core update - reverified file protection', ['source' => 'file_guard']);
        }
    }

    public function show_file_warnings() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        $perm_issues = get_option('botfend_permission_issues', []);
        if (!empty($perm_issues) && !$this->is_notice_dismissed('permissions')) {
            $this->render_permission_notice($perm_issues);
        }
        
        if ($this->config->get_bool('protect_uploads', false)) {
            $upload_dir = wp_get_upload_dir();
            $php_fallback = $upload_dir['basedir'] . '/index.php';
            
            if (!file_exists($php_fallback) && !$this->is_notice_dismissed('uploads')) {
                $this->render_unprotected_notice();
            }
        }
    }

    private function is_notice_dismissed($notice_id) {
        $user_id = get_current_user_id();
        if (!$user_id) {
            return false;
        }
        
        $dismissed = get_user_meta($user_id, self::NOTICE_PREFIX . $notice_id, true);
        
        if (!$dismissed) {
            return false;
        }
        
        if (time() - $dismissed > 30 * DAY_IN_SECONDS) {
            delete_user_meta($user_id, self::NOTICE_PREFIX . $notice_id);
            return false;
        }
        
        return true;
    }

    public function handle_notice_dismissal() {
        if (!check_ajax_referer('botfend_file_guard', 'nonce', false)) {
            wp_send_json_error(['message' => 'Invalid nonce']);
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $notice_id = isset($_POST['notice_id']) ? sanitize_key($_POST['notice_id']) : '';
            
        if (empty($notice_id)) {
            wp_send_json_error(['message' => 'Invalid notice ID']);
        }
        
        $user_id = get_current_user_id();
        update_user_meta($user_id, self::NOTICE_PREFIX . $notice_id, time());
        
        wp_send_json_success(['message' => 'Notice dismissed']);
    }

    public function ajax_protect_uploads() {
        if (!check_ajax_referer('botfend_file_guard', 'nonce', false)) {
            wp_send_json_error(['message' => 'Invalid nonce']);
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $result = $this->manually_protect_uploads();
        
        if ($result['success']) {
            wp_send_json_success([
                'message' => __('Uploads protection applied successfully!', 'botfend-anti-bot-firewall'),
                'status' => $result['status']
            ]);
        } else {
            wp_send_json_error([
                'message' => __('Failed to apply protection. Check error logs.', 'botfend-anti-bot-firewall')
            ]);
        }
    }

    public function ajax_check_permissions() {
        if (!check_ajax_referer('botfend_file_guard', 'nonce', false)) {
            wp_send_json_error(['message' => 'Invalid nonce']);
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $issues = $this->manually_check_permissions();
        
        wp_send_json_success([
            'message' => sprintf(
                __('Permission check complete. Found %d issues.', 'botfend-anti-bot-firewall'),
                count($issues)
            ),
            'issues' => $issues
        ]);
    }

    private function render_permission_notice($issues) {
        $count = isset($issues['count']) ? $issues['count'] : 0;
        if ($count === 0) {
            return;
        }
        ?>
        <div class="notice notice-warning is-dismissible botfend-notice" 
             data-notice-id="permissions"
             data-nonce="<?php echo esc_attr(wp_create_nonce('botfend_file_guard')); ?>">
            <p>
                <strong><?php esc_html_e('BotFend Anti-Bot Firewall:', 'botfend-anti-bot-firewall'); ?></strong>
                <?php echo esc_html(sprintf(
                    _n(
                        'Found %d file with insecure permissions.',
                        'Found %d files with insecure permissions.',
                        $count,
                        'botfend-anti-bot-firewall'
                    ),
                    $count
                )); ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings&tab=system')); ?>">
                    <?php esc_html_e('Review now', 'botfend-anti-bot-firewall'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    private function render_unprotected_notice() {
        ?>
        <div class="notice notice-warning is-dismissible botfend-notice" 
             data-notice-id="uploads"
             data-nonce="<?php echo esc_attr(wp_create_nonce('botfend_file_guard')); ?>">
            <p>
                <strong><?php esc_html_e('BotFend Anti-Bot Firewall:', 'botfend-anti-bot-firewall'); ?></strong>
                <?php esc_html_e('Your uploads directory is not fully protected.', 'botfend-anti-bot-firewall'); ?>
                <button type="button" class="button button-small botfend-protect-uploads">
                    <?php esc_html_e('Apply Protection Now', 'botfend-anti-bot-firewall'); ?>
                </button>
            </p>
        </div>
        <?php
    }

    private function send_alert($subject, $file, $details = '') {
        $admin_email = get_option('admin_email');
        if (!$admin_email) {
            return;
        }
        
        $site_name = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
        $full_subject = sprintf('[%s] BotFend Alert: %s', $site_name, $subject);
        
        $message = "BotFend Anti-Bot Firewall File Guard Alert\n\n";
        $message .= "Site: " . home_url() . "\n";
        $message .= "Time: " . current_time('mysql') . "\n";
        $message .= "Event: " . $subject . "\n";
        $message .= "File: " . $file . "\n";
        
        if (!empty($details)) {
            $message .= "Details: " . $details . "\n";
        }
        
        $message .= "\nThis alert can be disabled in BotFend settings.\n";
        
        wp_mail($admin_email, $full_subject, $message);
    }

    public function get_protection_status() {
        $upload_dir = wp_get_upload_dir();
        $htaccess_file = $upload_dir['basedir'] . '/.htaccess';
        $php_fallback = $upload_dir['basedir'] . '/index.php';
        
        $uploads_protected = false;
        $protection_methods = [];
        
        if (file_exists($php_fallback)) {
            $content = file_get_contents($php_fallback);
            if (strpos($content, 'BotFend Anti-Bot Firewall') !== false) {
                $uploads_protected = true;
                $protection_methods[] = 'PHP Fallback';
            }
        }
        
        if (file_exists($htaccess_file)) {
            $content = file_get_contents($htaccess_file);
            if (strpos($content, 'BotFend Anti-Bot Firewall') !== false) {
                $uploads_protected = true;
                $protection_methods[] = 'Server Config';
            }
        }
        
        return [
            'uploads_protected' => $uploads_protected,
            'protection_methods' => $protection_methods,
            'file_editors_disabled' => defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT,
            'file_mods_disabled' => defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS,
            'automatic_updates_disabled' => defined('AUTOMATIC_UPDATER_DISABLED') && AUTOMATIC_UPDATER_DISABLED,
            'htaccess_exists' => file_exists($htaccess_file),
            'php_fallback_exists' => file_exists($php_fallback),
            'index_exists' => file_exists($upload_dir['basedir'] . '/index.php'),
            'scan_uploads_enabled' => $this->config->get_bool('scan_uploads', false),
            'auto_fix_permissions' => $this->config->get_bool('auto_fix_permissions', false),
            'monitor_permissions' => $this->config->get_bool('monitor_permissions', false),
            'protect_uploads' => $this->config->get_bool('protect_uploads', false),
            'alert_on_change' => $this->config->get_bool('alert_on_file_change', false),
            'blocked_extensions' => $this->get_blocked_extensions(),
            'server_software' => $this->server_software,
            'is_litespeed' => $this->is_litespeed(),
            'permission_issues' => (int) get_option('botfend_permission_issues', 0),
            'cron_jobs_active' => $this->check_cron_jobs(),
            'filesystem_available' => ($this->wp_filesystem instanceof \WP_Filesystem_Base)
        ];
    }

    private function is_litespeed() {
        return (
            stripos($this->server_software, 'litespeed') !== false ||
            stripos($this->server_software, 'lsapi') !== false ||
            isset($_SERVER['LSAPI_']) ||
            isset($_SERVER['LITESPEED_'])
        );
    }

    private function check_cron_jobs() {
        return [
            'weekly' => (bool) wp_next_scheduled('botfend_file_guard_weekly'),
            'daily' => (bool) wp_next_scheduled('botfend_file_guard_daily'),
        ];
    }

    public function manually_protect_uploads() {
        delete_transient('botfend_uploads_secured');
        $this->secure_uploads_directory();
        
        $status = $this->get_protection_status();
        
        return [
            'success' => $status['uploads_protected'],
            'status' => $status
        ];
    }

    public function manually_check_permissions() {
        $issues = $this->check_file_permissions();
        
        if (empty($issues)) {
            $user_id = get_current_user_id();
            delete_user_meta($user_id, self::NOTICE_PREFIX . 'permissions');
        }
        
        return $issues;
    }

    private function get_client_ip() {
        $headers = [
            'HTTP_CF_CONNECTING_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_REAL_IP',
            'HTTP_CLIENT_IP',
            'REMOTE_ADDR'
        ];
        
        foreach ($headers as $header) {
            if (isset($_SERVER[$header])) {
                $ip = sanitize_text_field(wp_unslash($_SERVER[$header]));
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }
        
        return '0.0.0.0';
    }
}