<?php
/**
 * Plugin Deactivator for BotFend Anti-Bot Firewall
 *
 * @package BotFend\Core
 */

namespace BotFend\Core;

defined('ABSPATH') || exit;

class Deactivator {

    public function deactivate(): void {
        try {
            $this->clear_scheduled_hooks();
            $this->cleanup_htaccess();
            $this->cleanup_firewall_directives();
            $this->clear_temporary_data();
            $this->flush_caches();
            $this->log_deactivation();
            do_action('botfend_defender_deactivated');
        } catch (\Throwable $e) {
            error_log('BotFend Deactivation Error: ' . $e->getMessage());
        }
    }

    private function clear_scheduled_hooks(): void {
        $hooks = [
            'botfend_daily_maintenance', 'botfend_update_threat_intel', 'botfend_update_tor_nodes',
            'botfend_auto_unblock', 'botfend_import_tor_nodes', 'botfend_file_guard_weekly',
            'botfend_file_guard_daily', 'botfend_cleanup_transients', 'botfend_fingerprint_cleanup',
            'botfend_calculate_enhanced_attack_level', 'botfend_update_threat_feeds',
            'botfend_preload_threat_feeds', 'botfend_cleanup_sessions',
        ];
        $cron = _get_cron_array();
        if (is_array($cron)) {
            $changed = false;
            foreach ($cron as $timestamp => $cronhooks) {
                foreach ($hooks as $hook) {
                    if (isset($cronhooks[$hook])) {
                        unset($cron[$timestamp][$hook]);
                        $changed = true;
                    }
                }
                if (empty($cron[$timestamp])) {
                    unset($cron[$timestamp]);
                }
            }
            if ($changed) {
                _set_cron_array($cron);
            }
        }
        if (class_exists('BotFend\Detection\ThreatIntel')) {
            \BotFend\Detection\ThreatIntel::clear_schedule();
        }
    }

    private function cleanup_htaccess(): void {
        // Initialize WordPress Filesystem
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            WP_Filesystem();
        }

        // Use plugin-specific directory instead of uploads root
        $upload_dir = wp_upload_dir();
        $plugin_upload_dir = $upload_dir['basedir'] . '/botfend-security/';
        $htaccess_file = $plugin_upload_dir . '.htaccess';

        // Clean up plugin-specific .htaccess
        if ($wp_filesystem->exists($htaccess_file) && $wp_filesystem->is_writable($htaccess_file)) {
            $content = $wp_filesystem->get_contents($htaccess_file);
            if ($content !== false) {
                $pattern = '/# BotFend Anti-Bot Firewall Multi-Layer Protection.*?# End BotFend Anti-Bot Firewall/s';
                $new_content = preg_replace($pattern, '', $content);
                $new_content = preg_replace("/\n{3,}/", "\n\n", $new_content);
                $new_content = trim($new_content);
                if ($new_content !== $content) {
                    $wp_filesystem->put_contents($htaccess_file, $new_content . PHP_EOL, FS_CHMOD_FILE);
                }
                // Remove file if empty (only BotFend rules existed)
                if (empty(trim($new_content))) {
                    $wp_filesystem->delete($htaccess_file);
                }
            }
        }

        // Clean up legacy uploads root .htaccess if it exists (backward compatibility)
        $legacy_htaccess = $upload_dir['basedir'] . '/.htaccess';
        if ($wp_filesystem->exists($legacy_htaccess) && $wp_filesystem->is_writable($legacy_htaccess)) {
            $content = $wp_filesystem->get_contents($legacy_htaccess);
            if ($content !== false && strpos($content, 'BotFend') !== false) {
                $pattern = '/# BotFend Anti-Bot Firewall Multi-Layer Protection.*?# End BotFend Anti-Bot Firewall/s';
                $new_content = preg_replace($pattern, '', $content);
                $new_content = preg_replace("/\n{3,}/", "\n\n", $new_content);
                $new_content = trim($new_content);
                if ($new_content !== $content) {
                    $wp_filesystem->put_contents($legacy_htaccess, $new_content . PHP_EOL, FS_CHMOD_FILE);
                }
                if (empty(trim($new_content))) {
                    $wp_filesystem->delete($legacy_htaccess);
                }
            }
        }

        // Clean up web.config in plugin-specific directory
        $web_config = $plugin_upload_dir . 'web.config';
        if ($wp_filesystem->exists($web_config) && $wp_filesystem->is_writable($web_config)) {
            $content = $wp_filesystem->get_contents($web_config);
            if ($content !== false && strpos($content, 'BotFend') !== false) {
                $wp_filesystem->delete($web_config);
            }
        }

        // Clean up legacy web.config (backward compatibility)
        $legacy_web_config = $upload_dir['basedir'] . '/web.config';
        if ($wp_filesystem->exists($legacy_web_config) && $wp_filesystem->is_writable($legacy_web_config)) {
            $content = $wp_filesystem->get_contents($legacy_web_config);
            if ($content !== false && strpos($content, 'BotFend') !== false) {
                $wp_filesystem->delete($legacy_web_config);
            }
        }

        // Ensure plugin directory has index.php for security
        $index_file = $plugin_upload_dir . 'index.php';
        if (!$wp_filesystem->exists($index_file)) {
            $wp_filesystem->put_contents($index_file, '<?php // Silence is golden', FS_CHMOD_FILE);
        }
    }

    private function cleanup_firewall_directives(): void {
        $this->cleanup_user_ini_firewall();
        $this->cleanup_root_htaccess_firewall();
        delete_transient('botfend_firewall_pending');
    }

    private function cleanup_user_ini_firewall(): void {
        $user_ini_file = ABSPATH . '.user.ini';
        
        // Initialize WordPress Filesystem if not already done
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            WP_Filesystem();
        }

        if (!$wp_filesystem->exists($user_ini_file) || !$wp_filesystem->is_writable($user_ini_file)) {
            return;
        }

        $content = $wp_filesystem->get_contents($user_ini_file);
        if ($content === false) {
            return;
        }

        $content = preg_replace('/^; BotFend Anti-Bot Firewall.*$/m', '', $content);
        $content = preg_replace('/^auto_prepend_file\s*=.*$/m', '', $content);
        $content = preg_replace("/\n{3,}/", "\n\n", trim($content));

        $wp_filesystem->put_contents($user_ini_file, $content, FS_CHMOD_FILE);

        if (function_exists('opcache_invalidate')) {
            opcache_invalidate($user_ini_file, true);
        }
    }

    private function cleanup_root_htaccess_firewall(): void {
        $htaccess_file = ABSPATH . '.htaccess';
        
        // Initialize WordPress Filesystem if not already done
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            WP_Filesystem();
        }

        if (!$wp_filesystem->exists($htaccess_file) || !$wp_filesystem->is_writable($htaccess_file)) {
            return;
        }

        $content = $wp_filesystem->get_contents($htaccess_file);
        if ($content === false) {
            return;
        }

        $pattern = '/# BotFend Firewall.*?# End BotFend Firewall\n/s';
        $content = preg_replace($pattern, '', $content);

        $wp_filesystem->put_contents($htaccess_file, $content, FS_CHMOD_FILE);
    }

    private function clear_temporary_data(): void {
        global $wpdb;
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_botfend\_%' OR option_name LIKE '\_transient\_timeout\_botfend\_%'");
        $temp_options = [
            'botfend_recent_errors', 'botfend_session_error_count', 'botfend_threat_intel_errors',
            'botfend_last_auto_unblock', 'botfend_tor_last_update', 'botfend_feed_performance_stats',
            'botfend_last_optimization', 'botfend_algorithm_params', 'botfend_effectiveness_log',
        ];
        $placeholders = implode(', ', array_fill(0, count($temp_options), '%s'));
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is built from a fixed array of safe values
        $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name IN ($placeholders)", ...$temp_options));
        $queue_table = $wpdb->prefix . 'botfend_dedup_queue';
        if ($wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table) {
            $suppress = $wpdb->suppress_errors();
            $result = $wpdb->query("TRUNCATE TABLE `$queue_table`");
            if ($result === false) {
                $wpdb->query("DELETE FROM `$queue_table`");
            }
            $wpdb->suppress_errors($suppress);
        }
    }

    private function flush_caches(): void {
        $cache_groups = ['botfend_defender', 'botfend_admin', 'botfend_config', 'botfend_sessions'];
        foreach ($cache_groups as $group) {
            if (function_exists('wp_cache_flush_group')) {
                wp_cache_flush_group($group);
            }
        }
        if (class_exists('BotFend\Core\Config')) {
            Config::get_instance()->clear_cache();
        }
        if (class_exists('BotFend\Core\Autoloader')) {
            Autoloader::clear_cache();
        }
    }

    private function log_deactivation(): void {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('BotFend v' . BOTFEND_VERSION . ' Deactivated.');
        }
    }
}