<?php
/**
 * Guardify Admin Class
 * Version: 1.0.7
 */
class Guardify_Admin {
    public function __construct() {
        add_action('admin_menu', [$this, 'add_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('wp_ajax_guardify_toggle_firewall', [$this, 'toggle_firewall']);
        add_action('wp_ajax_guardify_reset_settings', [$this, 'reset_settings']);
        add_action('wp_ajax_guardify_add_ip_rule', [$this, 'add_ip_rule']);
        add_action('wp_ajax_guardify_remove_ip_rule', [$this, 'remove_ip_rule']);
        // Register AJAX handler for ByteDefense installation
        add_action('wp_ajax_guardify_install_bytedefense', [$this, 'install_bytedefense']);
    }

    public function add_menu() {
        add_menu_page(
            esc_html__('Guardify', 'guardify'),
            esc_html__('Guardify', 'guardify'),
            'manage_options',
            'guardify-dashboard',
            [$this, 'render_dashboard'],
            'dashicons-shield'
        );
        add_submenu_page(
            'guardify-dashboard',
            esc_html__('Dashboard', 'guardify'),
            esc_html__('Dashboard', 'guardify'),
            'manage_options',
            'guardify-dashboard',
            [$this, 'render_dashboard']
        );
        add_submenu_page(
            'guardify-dashboard',
            esc_html__('Statistics', 'guardify'),
            esc_html__('Statistics', 'guardify'),
            'manage_options',
            'guardify-statistics',
            [$this, 'render_statistics']
        );
        add_submenu_page(
            'guardify-dashboard',
            esc_html__('IP Rules', 'guardify'),
            esc_html__('IP Rules', 'guardify'),
            'manage_options',
            'guardify-ip-rules',
            [$this, 'render_ip_rules_page']
        );
        add_submenu_page(
            'guardify-dashboard',
            esc_html__('Settings', 'guardify'),
            esc_html__('Settings', 'guardify'),
            'manage_options',
            'guardify-settings',
            [$this, 'render_settings']
        );
    }

    public function enqueue_assets($hook) {
        if (strpos($hook, 'guardify') === false) return;
        wp_enqueue_style('guardify-style', GUARDIFY_URL . 'assets/style.css');
        wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', [], null, true);
        wp_enqueue_script('guardify-script', GUARDIFY_URL . 'assets/script.js', ['jquery', 'chart-js'], null, true);

        if (isset($_REQUEST['page']) && $_REQUEST['page'] == 'guardify-statistics') {
            $inline_js = "
            jQuery(document).ready(function($) {
                loadStats();
                
                // Load stats
                function loadStats() {
                    var period = $('#statsPeriod').val();
                    
                    const canvas = document.getElementById('activityChart');
                    const ctx = canvas.getContext('2d');
                    
                    if (activityChart) {
                        activityChart.destroy();
                    }
                    
                    var data = {
                        labels: ['Blocked', 'Allowed', 'Logins'],
                        datasets: [{
                            label: 'Activity',
                            data: [10 * period, 50 * period, 20 * period],
                            backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
                        }]
                    };
                    activityChart = new Chart($('#activityChart'), {
                        type: 'bar',
                        data: data,
                        options: { responsive: true }
                    });
                }
                $('#statsPeriod').change(loadStats);
            });
        ";
            wp_add_inline_script('guardify-script', $inline_js);
        }

        // Add AJAX handler for ByteDefense installation on all Guardify pages
        $inline_js = "
        jQuery(document).ready(function($) {
            $('#install-bytedefense').click(function(e) {
                e.preventDefault();
                var button = $(this);
                button.prop('disabled', true).after('<span class=\"guardify-loader\"></span>');

                // Log AJAX data for debugging
                console.log('AJAX Data:', {
                    action: 'guardify_install_bytedefense',
                    nonce: guardifyAjax.nonce
                });
                
                $.ajax({
                    url: guardifyAjax.ajax_url,
                    method: 'POST',
                    data: {
                        action: 'guardify_install_bytedefense',
                        nonce: guardifyAjax.nonce
                    },
                    success: function(response) {
                        console.log('AJAX Success:', response);
                        if (response.success) {
                            window.location.href = response.data.redirect;
                        } else {
                            alert('Failed to install ByteDefense: ' + response.data.message);
                            button.prop('disabled', false);
                            $('.guardify-loader').remove();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log('AJAX Error:', { status: status, error: error, response: xhr.responseText });
                        alert('An error occurred while installing ByteDefense: ' + error + ' (Status: ' + status + ')');
                        button.prop('disabled', false);
                        $('.guardify-loader').remove();
                    }
                });
            });
        });
    ";
        wp_add_inline_script('guardify-script', $inline_js);

        // Localize script with AJAX URL and nonce
        wp_localize_script('guardify-script', 'guardifyAjax', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('guardify_nonce'),
        ]);
    }

    public function toggle_firewall() {
        check_ajax_referer('guardify_nonce', 'nonce');
        $settings = get_option('guardify_settings', []);
        $settings['enabled'] = !empty($_POST['enable']) ? 1 : 0;
        update_option('guardify_settings', $settings);
        wp_send_json_success(['enabled' => $settings['enabled']]);
    }

    public function reset_settings() {
        check_ajax_referer('guardify_nonce', 'nonce');
        $default_settings = [
            'enabled' => 0,
            'block_bruteforce' => 1,
            'notify_login_country_change' => 1,
            'advanced_bot_control' => 0,
            'enable_2fa' => 0,
            'rate_limit' => 1000, // Changed to requests/hour
            'blocked_user_agents' => 'bot,scanner,crawler',
            'geo_block_countries' => '',
            'block_plugin_theme_install' => 0,
            'block_theme_editor' => 0,
            'forbidden_comment_words' => 'http,https,www,viagra,casino,porn',
            'auto_block_ip_htaccess' => 0,
        ];
        update_option('guardify_settings', $default_settings);
        delete_option('guardify_ip_rules');
        wp_send_json_success(['message' => esc_html__('Settings reset to default.', 'guardify')]);
    }

    public function add_ip_rule() {
        check_ajax_referer('guardify_nonce', 'nonce');
        $ip = sanitize_text_field($_POST['ip']);
        $type = sanitize_text_field($_POST['type']);
        $description = sanitize_text_field($_POST['description']);
        $expiry = sanitize_text_field($_POST['expiry']);

        if (empty($ip) || !in_array($type, ['allow', 'block'])) {
            wp_send_json_error(['message' => esc_html__('Invalid IP or rule type.', 'guardify')]);
        }

        $ip_rules = get_option('guardify_ip_rules', []);
        $ip_rules[] = [
            'ip' => $ip,
            'type' => $type,
            'description' => $description,
            'expiry' => $expiry,
            'created' => current_time('mysql'),
        ];
        update_option('guardify_ip_rules', $ip_rules);
        wp_send_json_success(['message' => esc_html__('IP rule added.', 'guardify')]);
    }

    public function remove_ip_rule() {
        check_ajax_referer('guardify_nonce', 'nonce');
        $index = intval($_POST['index']);
        $ip_rules = get_option('guardify_ip_rules', []);
        if (isset($ip_rules[$index])) {
            unset($ip_rules[$index]);
            $ip_rules = array_values($ip_rules);
            update_option('guardify_ip_rules', $ip_rules);
            wp_send_json_success(['message' => esc_html__('IP rule removed.', 'guardify')]);
        }
        wp_send_json_error(['message' => esc_html__('Rule not found.', 'guardify')]);
    }

    // Handle ByteDefense installation via AJAX
    public function install_bytedefense() {
        // Ensure no output before JSON response
        if (ob_get_length()) {
            ob_clean();
        }

        // Check nonce
        if (!check_ajax_referer('guardify_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => esc_html__('Security check failed. Please try again.', 'guardify')]);
            exit;
        }

        // Ensure user session
        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('User session expired. Please log in again.', 'guardify')]);
            exit;
        }

        // Check user capability
        if (!current_user_can('install_plugins') || !current_user_can('activate_plugins')) {
            wp_send_json_error(['message' => esc_html__('Permission denied: You do not have the required permissions to install and activate plugins.', 'guardify')]);
            exit;
        }

        // Include necessary WordPress files
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/misc.php';
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/plugin-install.php';

        // Define plugin slug and path
        $plugin_slug = 'bytedefense';
        $plugin_file = $plugin_slug . '/' . $plugin_slug . '.php';

        // Log: Starting process
        error_log('Guardify: Starting ByteDefense plugin installation');

        // Check if plugin is already active
        if (is_plugin_active($plugin_file)) {
            error_log('Guardify: ByteDefense plugin is already active');
            wp_send_json_success(['redirect' => admin_url('admin.php?page=bytedefense')]);
            exit;
        }

        // Check write permissions for plugins directory
        $plugins_dir = WP_PLUGIN_DIR;
        if (!is_writable($plugins_dir)) {
            error_log('Guardify: Plugins directory is not writable');
            wp_send_json_error(['message' => esc_html__('The plugins directory (/wp-content/plugins/) is not writable. Please check directory permissions and try again.', 'guardify')]);
            exit;
        }

        // Step 1: Download plugin from WordPress.org
        error_log('Guardify: Retrieving plugin information from WordPress.org');
        $api = plugins_api('plugin_information', [
            'slug' => $plugin_slug,
            'fields' => ['sections' => false],
        ]);

        // If plugin is not found in WordPress repository, use a fallback URL
        if (is_wp_error($api)) {
            error_log('Guardify: Failed to retrieve plugin information from WordPress.org - ' . $api->get_error_message());
            wp_send_json_error(['message' => esc_html__('ByteDefense plugin not found in WordPress repository. Please install it manually or contact support.', 'guardify')]);
            exit;
        } else {
            $download_link = $api->download_link;
        }

        // Step 2: Install plugin
        error_log('Guardify: Installing ByteDefense plugin from ' . $download_link);
        $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
        $install_result = $upgrader->install($download_link);

        if (is_wp_error($install_result)) {
            error_log('Guardify: Installation failed - ' . $install_result->get_error_message());
            wp_send_json_error(['message' => esc_html__('Failed to install the ByteDefense plugin: ', 'guardify') . $install_result->get_error_message()]);
            exit;
        }

        if ($install_result !== true) {
            error_log('Guardify: Installation returned unexpected result');
            wp_send_json_error(['message' => esc_html__('Plugin installation failed. Please check your server logs or try installing manually.', 'guardify')]);
            exit;
        }

        // Step 3: Verify installation
        $plugin_full_path = WP_PLUGIN_DIR . '/' . $plugin_file;
        if (!file_exists($plugin_full_path)) {
            error_log('Guardify: Main plugin file not found after installation');
            wp_send_json_error(['message' => esc_html__('Main plugin file (bytedefense.php) not found after installation. Installation may have failed.', 'guardify')]);
            exit;
        }

        // Step 4: Activate plugin
        error_log('Guardify: Activating ByteDefense plugin');
        $activate = activate_plugin($plugin_file);
        if (is_wp_error($activate)) {
            error_log('Guardify: Activation failed - ' . $activate->get_error_message());
            wp_send_json_error(['message' => esc_html__('Failed to activate the ByteDefense plugin: ', 'guardify') . $activate->get_error_message()]);
            exit;
        }

        error_log('Guardify: ByteDefense plugin installed and activated successfully');
        wp_send_json_success(['redirect' => admin_url('admin.php?page=bytedefense')]);
        exit;
    }

    // Render Antivirus Plugin Recommendation block
    private function render_antivirus_recommendation() {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        if (!is_plugin_active('bytedefense/bytedefense.php')) {
            ?>
            <div class="guardify-warning">
                <h3><?php esc_html_e('Antivirus Plugin Recommendation', 'guardify'); ?></h3>
                <p><?php esc_html_e('Antivirus ByteDefense is not installed. To keep your website files clean and secure, we strongly recommend installing this plugin.', 'guardify'); ?></p>
                <button id="install-bytedefense" class="button button-primary"><?php esc_html_e('Install ByteDefense', 'guardify'); ?></button>
            </div>
            <?php
        }
    }

    private function render_tabs($current_tab) {
        $tabs = [
            'dashboard' => ['title' => esc_html__('Dashboard', 'guardify'), 'icon' => 'dashicons-dashboard', 'url' => admin_url('admin.php?page=guardify-dashboard')],
            'stats' => ['title' => esc_html__('Statistics', 'guardify'), 'icon' => 'dashicons-chart-bar', 'url' => admin_url('admin.php?page=guardify-statistics')],
            'ip-rules' => ['title' => esc_html__('IP Rules', 'guardify'), 'icon' => 'dashicons-lock', 'url' => admin_url('admin.php?page=guardify-ip-rules')],
            'settings' => ['title' => esc_html__('Settings', 'guardify'), 'icon' => 'dashicons-admin-settings', 'url' => admin_url('admin.php?page=guardify-settings')],
        ];
        ?>
        <div class="guardify-tabs">
            <ul class="nav-tabs">
                <?php foreach ($tabs as $tab_id => $tab) : ?>
                    <li class="<?php echo $current_tab === $tab_id ? 'active' : ''; ?>">
                        <a href="<?php echo esc_url($tab['url']); ?>" data-icon="<?php echo esc_attr($tab['icon']); ?>">
                            <?php echo esc_html($tab['title']); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php
    }

    public function render_dashboard() {
        $settings = get_option('guardify_settings', []);
        $activity = $this->get_log_data(GUARDIFY_LOG_DIR . '/activity.log', 5);
        $blocks = $this->get_log_data(GUARDIFY_LOG_DIR . '/blocks.log', 5);
        $logins = $this->get_log_data(GUARDIFY_LOG_DIR . '/logins.log', 5);
        ?>
        <div class="wrap guardify-wrap">
            <h1><?php esc_html_e('Guardify', 'guardify'); ?></h1>
            <?php $this->render_antivirus_recommendation(); ?>
            <?php $this->render_tabs('dashboard'); ?>
            <div class="tab-content">
                <div id="dashboard" class="tab-pane active">
                    <div class="guardify-header">
                        <h2><?php esc_html_e('Security Dashboard', 'guardify'); ?></h2>
                        <p><?php esc_html_e('Your central hub for monitoring and managing site security. Enable the firewall, view recent activity, and stay informed.', 'guardify'); ?></p>
                    </div>
                    <button id="toggle-firewall" class="button button-primary" data-enabled="<?php echo esc_attr($settings['enabled'] ? 1 : 0); ?>">
                        <?php echo $settings['enabled'] ? esc_html__('Disable Firewall', 'guardify') : esc_html__('Enable Firewall', 'guardify'); ?>
                    </button>
                    <div class="guardify-stats">
                        <h3><?php esc_html_e('Recent Activity', 'guardify'); ?></h3>
                        <table class="widefat">
                            <thead><tr><th>IP</th><th>Time</th><th>Country</th><th>URI</th></tr></thead>
                            <tbody>
                                <?php foreach ($activity as $log) {
                                    echo '<tr><td>' . esc_html($log['ip']) . '</td><td>' . esc_html($log['time']) . '</td><td>' . esc_html($log['country']) . '</td><td>' . esc_html($log['uri']) . '</td></tr>';
                                } ?>
                            </tbody>
                        </table>
                        <h3><?php esc_html_e('Recent Blocks', 'guardify'); ?></h3>
                        <table class="widefat">
                            <thead><tr><th>IP</th><th>Time</th><th>Country</th><th>Reason</th></tr></thead>
                            <tbody>
                                <?php foreach ($blocks as $log) {
                                    echo '<tr><td>' . esc_html($log['ip']) . '</td><td>' . esc_html($log['time']) . '</td><td>' . esc_html($log['country']) . '</td><td>' . esc_html($log['reason']) . '</td></tr>';
                                } ?>
                            </tbody>
                        </table>
                        <h3><?php esc_html_e('Recent Logins', 'guardify'); ?></h3>
                        <table class="widefat">
                            <thead><tr><th>User</th><th>IP</th><th>Time</th><th>Country</th><th>Status</th></tr></thead>
                            <tbody>
                                <?php foreach ($logins as $log) {
                                    echo '<tr><td>' . esc_html($log['user']) . '</td><td>' . esc_html($log['ip']) . '</td><td>' . esc_html($log['time']) . '</td><td>' . esc_html($log['country']) . '</td><td>' . esc_html($log['status']) . '</td></tr>';
                                } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    public function render_statistics() {
        $logins = $this->get_log_data(GUARDIFY_LOG_DIR . '/logins.log', 5);
        ?>
        <div class="wrap guardify-wrap">
            <h1><?php esc_html_e('Guardify', 'guardify'); ?></h1>
            <?php $this->render_antivirus_recommendation(); ?>
            <?php $this->render_tabs('stats'); ?>
            <div class="tab-content">
                <div id="stats" class="tab-pane active">
                    <div class="guardify-header">
                        <h2><?php esc_html_e('Statistics', 'guardify'); ?></h2>
                        <p><?php esc_html_e('Detailed insights into your site’s security: login attempts, blocked threats, and traffic trends over time.', 'guardify'); ?></p>
                    </div>
                    <select id="statsPeriod">
                        <option value="1"><?php esc_html_e('1 Day', 'guardify'); ?></option>
                        <option value="3"><?php esc_html_e('3 Days', 'guardify'); ?></option>
                        <option value="7"><?php esc_html_e('7 Days', 'guardify'); ?></option>
                        <option value="30"><?php esc_html_e('30 Days', 'guardify'); ?></option>
                        <option value="90"><?php esc_html_e('3 Months', 'guardify'); ?></option>
                    </select>
                    <canvas id="activityChart"></canvas>
                    <h3><?php esc_html_e('Login History', 'guardify'); ?></h3>
                    <table class="widefat">
                        <thead><tr><th>User</th><th>IP</th><th>Time</th><th>Country</th><th>Status</th></tr></thead>
                        <tbody>
                            <?php foreach ($logins as $log) {
                                echo '<tr><td>' . esc_html($log['user']) . '</td><td>' . esc_html($log['ip']) . '</td><td>' . esc_html($log['time']) . '</td><td>' . esc_html($log['country']) . '</td><td>' . esc_html($log['status']) . '</td></tr>';
                            } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
    }

    public function render_ip_rules_page() {
        ?>
        <div class="wrap guardify-wrap">
            <h1><?php esc_html_e('Guardify', 'guardify'); ?></h1>
            <?php $this->render_antivirus_recommendation(); ?>
            <?php $this->render_tabs('ip-rules'); ?>
            <div class="tab-content">
                <div id="ip-rules" class="tab-pane active">
                    <div class="guardify-header">
                        <h2><?php esc_html_e('IP Rules', 'guardify'); ?></h2>
                        <p><?php esc_html_e('Manage IP-based access rules to allow or block specific IPs or subnets. Allow rules take precedence over block rules.', 'guardify'); ?></p>
                    </div>
                    <div class="guardify-ip-rules">
                        <div class="guardify-add-rule">
                            <h3><?php esc_html_e('Add IP Rule', 'guardify'); ?></h3>
                            <form id="add-ip-rule-form">
                                <p>
                                    <label for="ip-address"><?php esc_html_e('IP Address or CIDR Range', 'guardify'); ?></label>
                                    <input type="text" id="ip-address" name="ip" placeholder="e.g., 192.168.1.1 or 192.168.1.0/24">
                                </p>
                                <p>
                                    <label for="rule-type"><?php esc_html_e('Rule Type', 'guardify'); ?></label>
                                    <select id="rule-type" name="type">
                                        <option value="block"><?php esc_html_e('Block', 'guardify'); ?></option>
                                        <option value="allow"><?php esc_html_e('Allow', 'guardify'); ?></option>
                                    </select>
                                </p>
                                <p>
                                    <label for="rule-description"><?php esc_html_e('Description', 'guardify'); ?></label>
                                    <textarea id="rule-description" name="description" placeholder="Optional description"></textarea>
                                </p>
                                <p>
                                    <label for="rule-expiry"><?php esc_html_e('Expiry Date (Optional)', 'guardify'); ?></label>
                                    <input type="date" id="rule-expiry" name="expiry">
                                    <span class="description"><?php esc_html_e('Leave empty for permanent rules.', 'guardify'); ?></span>
                                </p>
                                <p>
                                    <button type="submit" class="button button-primary"><?php esc_html_e('Add Rule', 'guardify'); ?></button>
                                </p>
                            </form>
                        </div>
                        <div class="guardify-rule-list">
                            <h3><?php esc_html_e('IP Rules', 'guardify'); ?></h3>
                            <div class="guardify-filter-buttons">
                                <button class="button filter-button active" data-filter="all"><?php esc_html_e('All', 'guardify'); ?> (<span class="count"><?php echo count(get_option('guardify_ip_rules', [])); ?></span>)</button>
                                <button class="button filter-button" data-filter="allow"><?php esc_html_e('Allow', 'guardify'); ?></button>
                                <button class="button filter-button" data-filter="block"><?php esc_html_e('Block', 'guardify'); ?></button>
                            </div>
                            <table class="widefat guardify-ip-table">
                                <thead>
                                    <tr>
                                        <th><?php esc_html_e('IP Address', 'guardify'); ?></th>
                                        <th><?php esc_html_e('Description', 'guardify'); ?></th>
                                        <th><?php esc_html_e('Expiry', 'guardify'); ?></th>
                                        <th><?php esc_html_e('Actions', 'guardify'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="ip-rules-list">
                                    <?php $this->render_ip_rules(); ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    public function render_settings() {
        $settings = get_option('guardify_settings', []);
        if (isset($_POST['guardify_save']) && check_admin_referer('guardify_settings')) {
            $settings = array_map('sanitize_text_field', wp_unslash($_POST['guardify']));
            if (isset($_POST['guardify']['geo_block_countries']) && is_array($_POST['guardify']['geo_block_countries'])) {
                $settings['geo_block_countries'] = implode(',', array_map('sanitize_text_field', $_POST['guardify']['geo_block_countries']));
            } else {
                $settings['geo_block_countries'] = '';
            }
            update_option('guardify_settings', $settings);
            echo '<div class="notice notice-success"><p>' . esc_html__('Settings saved.', 'guardify') . '</p></div>';
        }
        ?>
        <div class="wrap guardify-wrap">
            <h1><?php esc_html_e('Guardify', 'guardify'); ?></h1>
            <?php $this->render_antivirus_recommendation(); ?>
            <?php $this->render_tabs('settings'); ?>
            <div class="tab-content">
                <div id="settings" class="tab-pane active">
                    <div class="guardify-header">
                        <h2><?php esc_html_e('Settings', 'guardify'); ?></h2>
                        <p><?php esc_html_e('Customize your firewall rules, configure advanced protection, and fine-tune security settings.', 'guardify'); ?></p>
                    </div>
                    <form method="post">
                        <?php wp_nonce_field('guardify_settings'); ?>
                        <h3><?php esc_html_e('Basic Settings', 'guardify'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th><?php esc_html_e('Rate Limit (requests/hour)', 'guardify'); ?></th>
                                <td>
                                    <input type="number" name="guardify[rate_limit]" value="<?php echo esc_attr($settings['rate_limit'] ?? 1000); ?>" min="1" max="10000">
                                    <p class="description">
                                        <?php esc_html_e('Set the maximum number of requests an IP address can make to your site per hour. This helps prevent brute force attacks, DDoS attempts, and excessive bot activity by limiting how often a single IP can access your site. For example, if set to 1000, an IP can make up to 1000 requests in an hour. If this limit is exceeded, the IP will be temporarily blocked until the next hour. A lower value increases security but may affect legitimate users on shared IPs (e.g., corporate networks). A higher value allows more requests but may reduce protection. Default is 1000 requests per hour.', 'guardify'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                        <h3><?php esc_html_e('Advanced Settings', 'guardify'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th><?php esc_html_e('Enable 2FA', 'guardify'); ?></th>
                                <td>
                                    <input type="checkbox" name="guardify[enable_2fa]" value="1" <?php checked($settings['enable_2fa'] ?? 0); ?>>
                                    <p class="description">
                                        <?php esc_html_e('Enable two-factor authentication (2FA) for admin logins to add an extra layer of security. When enabled, administrators will need to enter a time-based one-time password (TOTP) generated by an app like Google Authenticator in addition to their username and password. This helps protect your site from unauthorized access even if an admin’s password is compromised.', 'guardify'); ?>
                                        <br><br>
                                        <strong><?php esc_html_e('How to Set Up 2FA with Google Authenticator:', 'guardify'); ?></strong>
                                        <ol>
                                            <li><?php esc_html_e('Enable this option and save the settings.', 'guardify'); ?></li>
                                            <li><?php esc_html_e('Go to your user profile in the WordPress admin dashboard: ', 'guardify'); ?><a href="<?php echo esc_url(admin_url('profile.php')); ?>"><?php esc_html_e('Users > Profile', 'guardify'); ?></a>.</li>
                                            <li><?php esc_html_e('After enabling 2FA and saving the settings, you will see a QR code and a secret key for 2FA setup in your profile.', 'guardify'); ?></li>
                                            <li><?php esc_html_e('Download and install the Google Authenticator app on your smartphone (available for iOS and Android).', 'guardify'); ?></li>
                                            <li><?php esc_html_e('Open Google Authenticator and scan the QR code, or manually enter the secret key.', 'guardify'); ?></li>
                                            <li><?php esc_html_e('The app will generate a 6-digit code that changes every 30 seconds.', 'guardify'); ?></li>
                                            <li><?php esc_html_e('The next time you log in as an administrator, after entering your username and password, you will be prompted to enter the 6-digit code from Google Authenticator.', 'guardify'); ?></li>
                                        </ol>
                                        <?php esc_html_e('Note: Ensure you save the secret key in a secure place. If you lose access to your authenticator app, you will need this key to regain access. If you lose both the app and the key, you may need to disable 2FA via the database or by contacting your site administrator.', 'guardify'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Blocked User-Agents', 'guardify'); ?></th>
                                <td>
                                    <textarea name="guardify[blocked_user_agents]" class="guardify-textarea"><?php echo esc_textarea($settings['blocked_user_agents'] ?? 'bot,scanner,crawler'); ?></textarea>
                                    <p class="description"><?php esc_html_e('Comma-separated list of blocked User-Agent strings.', 'guardify'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Geo-Block Countries', 'guardify'); ?></th>
                                <td>
                                    <input type="text" id="country-search" placeholder="<?php esc_attr_e('Search countries...', 'guardify'); ?>" class="regular-text">
                                    <div class="guardify-country-list">
                                        <?php
                                        $selected_countries = !empty($settings['geo_block_countries']) ? explode(',', $settings['geo_block_countries']) : [];
                                        $countries = $this->get_country_list();
                                        foreach ($countries as $code => $name) {
                                            $checked = in_array($code, $selected_countries) ? 'checked' : '';
                                            echo '<label class="guardify-country-item">';
                                            echo '<input type="checkbox" name="guardify[geo_block_countries][]" value="' . esc_attr($code) . '" ' . esc_attr($checked) . '>';
                                            echo esc_html($name) . ' (' . esc_html($code) . ')';
                                            echo '</label>';
                                        }
                                        ?>
                                    </div>
                                    <p class="description"><?php esc_html_e('Select countries to block.', 'guardify'); ?></p>
                                </td>
                            </tr>
                        </table>
                        <h3><?php esc_html_e('WordPress Security', 'guardify'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th><?php esc_html_e('Block Plugin and Theme Installation', 'guardify'); ?></th>
                                <td>
                                    <input type="checkbox" name="guardify[block_plugin_theme_install]" value="1" <?php checked($settings['block_plugin_theme_install'] ?? 0); ?>>
                                    <p class="description">
                                        <?php esc_html_e('When enabled, this option prevents all users (including administrators) from installing new plugins or themes through the WordPress admin dashboard. This can help reduce the risk of unauthorized or malicious code being added to your site. Note: You can still install plugins and themes manually via FTP if this option is enabled.', 'guardify'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Block Theme Editor', 'guardify'); ?></th>
                                <td>
                                    <input type="checkbox" name="guardify[block_theme_editor]" value="1" <?php checked($settings['block_theme_editor'] ?? 0); ?>>
                                    <p class="description">
                                        <?php esc_html_e('When enabled, this option disables access to the Theme Editor in the WordPress admin dashboard (/wp-admin/theme-editor.php). The Theme Editor allows direct editing of theme files, which can be a security risk if an attacker gains access to an admin account. Disabling this feature is recommended for most sites to prevent accidental or malicious changes to theme files.', 'guardify'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Forbidden Comment Words', 'guardify'); ?></th>
                                <td>
                                    <textarea name="guardify[forbidden_comment_words]" class="guardify-textarea"><?php echo esc_textarea($settings['forbidden_comment_words'] ?? 'http,https,www,viagra,casino,porn'); ?></textarea>
                                    <p class="description">
                                        <?php esc_html_e('Enter a comma-separated list of words or phrases that are not allowed in comments. If a comment contains any of these words, it will be automatically marked as spam. This helps prevent spam comments that include links (e.g., "http", "https", "www") or common spam keywords (e.g., "viagra", "casino"). The check is case-insensitive, so "HTTP" and "http" are treated the same. Leave this field empty to disable this feature.', 'guardify'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Auto Block IPs in .htaccess', 'guardify'); ?></th>
                                <td>
                                    <input type="checkbox" name="guardify[auto_block_ip_htaccess]" value="1" <?php checked($settings['auto_block_ip_htaccess'] ?? 0); ?>>
                                    <p class="description">
                                        <?php esc_html_e('When enabled, IPs that exceed the Rate Limit (requests/hour) will be automatically added to the .htaccess file for permanent blocking. This provides an additional layer of protection by denying access at the server level, preventing the IP from making any further requests to your site. Note: Ensure that your .htaccess file is writable by the server, and be cautious as this will permanently block the IP until manually removed from the .htaccess file. Use this feature carefully, as legitimate users on shared IPs (e.g., corporate networks) may also be affected.', 'guardify'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                        <p>
                            <input type="submit" name="guardify_save" class="button button-primary" value="<?php esc_attr_e('Save Settings', 'guardify'); ?>">
                            <button type="button" id="reset-settings" class="button button-secondary"><?php esc_html_e('Reset Settings', 'guardify'); ?></button>
                        </p>
                    </form>
                </div>
            </div>
        </div>
        <?php
    }

    private function render_ip_rules($filter = 'all') {
        $ip_rules = get_option('guardify_ip_rules', []);
        if (empty($ip_rules)) {
            echo '<tr><td colspan="4">' . esc_html__('No IP rules found.', 'guardify') . '</td></tr>';
            return;
        }

        foreach ($ip_rules as $index => $rule) {
            if ($filter !== 'all' && $rule['type'] !== $filter) continue;
            $class = $rule['type'] === 'allow' ? 'ip-allow' : 'ip-block';
            $expiry = empty($rule['expiry']) ? esc_html__('Never', 'guardify') : esc_html($rule['expiry']);
            echo '<tr class="' . esc_attr($class) . '">';
            echo '<td>' . esc_html($rule['ip']) . '</td>';
            echo '<td>' . esc_html($rule['description']) . ' (' . esc_html__('Created', 'guardify') . ': ' . esc_html($rule['created']) . ')</td>';
            echo '<td>' . esc_html($expiry) . '</td>';
            echo '<td><button class="button button-small button-danger remove-ip-rule" data-index="' . esc_attr($index) . '">' . esc_html__('Remove', 'guardify') . '</button></td>';
            echo '</tr>';
        }
    }

    private function get_log_data($file, $limit) {
        if (!file_exists($file)) return [];
        $lines = array_slice(file($file), -$limit);
        return array_map(function($line) {
            return json_decode($line, true);
        }, $lines);
    }

    private function get_country_list() {
        return [
            'AF' => 'Afghanistan',
            'AL' => 'Albania',
            'DZ' => 'Algeria',
            'AS' => 'American Samoa',
            'AD' => 'Andorra',
            'AO' => 'Angola',
            'AI' => 'Anguilla',
            'AQ' => 'Antarctica',
            'AG' => 'Antigua and Barbuda',
            'AR' => 'Argentina',
            'AM' => 'Armenia',
            'AW' => 'Aruba',
            'AU' => 'Australia',
            'AT' => 'Austria',
            'AZ' => 'Azerbaijan',
            'BS' => 'Bahamas',
            'BH' => 'Bahrain',
            'BD' => 'Bangladesh',
            'BB' => 'Barbados',
            'BY' => 'Belarus',
            'BE' => 'Belgium',
            'BZ' => 'Belize',
            'BJ' => 'Benin',
            'BM' => 'Bermuda',
            'BT' => 'Bhutan',
            'BO' => 'Bolivia',
            'BA' => 'Bosnia and Herzegovina',
            'BW' => 'Botswana',
            'BR' => 'Brazil',
            'IO' => 'British Indian Ocean Territory',
            'VG' => 'British Virgin Islands',
            'BN' => 'Brunei',
            'BG' => 'Bulgaria',
            'BF' => 'Burkina Faso',
            'BI' => 'Burundi',
            'KH' => 'Cambodia',
            'CM' => 'Cameroon',
            'CA' => 'Canada',
            'CV' => 'Cape Verde',
            'KY' => 'Cayman Islands',
            'CF' => 'Central African Republic',
            'TD' => 'Chad',
            'CL' => 'Chile',
            'CN' => 'China',
            'CX' => 'Christmas Island',
            'CC' => 'Cocos Islands',
            'CO' => 'Colombia',
            'KM' => 'Comoros',
            'CK' => 'Cook Islands',
            'CR' => 'Costa Rica',
            'HR' => 'Croatia',
            'CU' => 'Cuba',
            'CW' => 'Curacao',
            'CY' => 'Cyprus',
            'CZ' => 'Czech Republic',
            'CD' => 'Democratic Republic of the Congo',
            'DK' => 'Denmark',
            'DJ' => 'Djibouti',
            'DM' => 'Dominica',
            'DO' => 'Dominican Republic',
            'TL' => 'East Timor',
            'EC' => 'Ecuador',
            'EG' => 'Egypt',
            'SV' => 'El Salvador',
            'GQ' => 'Equatorial Guinea',
            'ER' => 'Eritrea',
            'EE' => 'Estonia',
            'ET' => 'Ethiopia',
            'FK' => 'Falkland Islands',
            'FO' => 'Faroe Islands',
            'FJ' => 'Fiji',
            'FI' => 'Finland',
            'FR' => 'France',
            'PF' => 'French Polynesia',
            'GA' => 'Gabon',
            'GM' => 'Gambia',
            'GE' => 'Georgia',
            'DE' => 'Germany',
            'GH' => 'Ghana',
            'GI' => 'Gibraltar',
            'GR' => 'Greece',
            'GL' => 'Greenland',
            'GD' => 'Grenada',
            'GU' => 'Guam',
            'GT' => 'Guatemala',
            'GG' => 'Guernsey',
            'GN' => 'Guinea',
            'GW' => 'Guinea-Bissau',
            'GY' => 'Guyana',
            'HT' => 'Haiti',
            'HN' => 'Honduras',
            'HK' => 'Hong Kong',
            'HU' => 'Hungary',
            'IS'  => 'Iceland',
            'IN' => 'India',
            'ID' => 'Indonesia',
            'IR' => 'Iran',
            'IQ' => 'Iraq',
            'IE' => 'Ireland',
            'IM' => 'Isle of Man',
            'IL' => 'Israel',
            'IT' => 'Italy',
            'CI' => 'Ivory Coast',
            'JM' => 'Jamaica',
            'JP' => 'Japan',
            'JE' => 'Jersey',
            'JO' => 'Jordan',
            'KZ' => 'Kazakhstan',
            'KE' => 'Kenya',
            'KI' => 'Kiribati',
            'XK' => 'Kosovo',
            'KW' => 'Kuwait',
            'KG' => 'Kyrgyzstan',
            'LA' => 'Laos',
            'LV' => 'Latvia',
            'LB' => 'Lebanon',
            'LS' => 'Lesotho',
            'LR' => 'Liberia',
            'LY' => 'Libya',
            'LI' => 'Liechtenstein',
            'LT' => 'Lithuania',
            'LU' => 'Luxembourg',
            'MO' => 'Macau',
            'MK' => 'Macedonia',
            'MG' => 'Madagascar',
            'MW' => 'Malawi',
            'MY' => 'Malaysia',
            'MV' => 'Maldives',
            'ML' => 'Mali',
            'MT' => 'Malta',
            'MH' => 'Marshall Islands',
            'MR' => 'Mauritania',
            'MU' => 'Mauritius',
            'YT' => 'Mayotte',
            'MX' => 'Mexico',
            'FM' => 'Micronesia',
            'MD' => 'Moldova',
            'MC' => 'Monaco',
            'MN' => 'Mongolia',
            'ME' => 'Montenegro',
            'MS' => 'Montserrat',
            'MA' => 'Morocco',
            'MZ' => 'Mozambique',
            'MM' => 'Myanmar',
            'NA' => 'Namibia',
            'NR' => 'Nauru',
            'NP' => 'Nepal',
            'NL' => 'Netherlands',
            'AN' => 'Netherlands Antilles',
            'NC' => 'New Caledonia',
            'NZ' => 'New Zealand',
            'NI' => 'Nicaragua',
            'NE' => 'Niger',
            'NG' => 'Nigeria',
            'NU' => 'Niue',
            'MP' => 'Northern Mariana Islands',
            'NO' => 'Norway',
            'OM' => 'Oman',
            'PK' => 'Pakistan',
            'PW' => 'Palau',
            'PS' => 'Palestine',
            'PA' => 'Panama',
            'PG' => 'Papua New Guinea',
            'PY' => 'Paraguay',
            'PE' => 'Peru',
            'PH' => 'Philippines',
            'PN' => 'Pitcairn',
            'PL' => 'Poland',
            'PT' => 'Portugal',
            'PR' => 'Puerto Rico',
            'QA' => 'Qatar',
            'CG' => 'Republic of the Congo',
            'RE' => 'Reunion',
            'RO' => 'Romania',
            'RU' => 'Russia',
            'RW' => 'Rwanda',
            'BL' => 'Saint Barthelemy',
            'SH' => 'Saint Helena',
            'KN' => 'Saint Kitts and Nevis',
            'LC' => 'Saint Lucia',
            'MF' => 'Saint Martin',
            'PM' => 'Saint Pierre and Miquelon',
            'VC' => 'Saint Vincent and the Grenadines',
            'WS' => 'Samoa',
            'SM' => 'San Marino',
            'ST' => 'Sao Tome and Principe',
            'SA' => 'Saudi Arabia',
            'SN' => 'Senegal',
            'RS' => 'Serbia',
            'SC' => 'Seychelles',
            'SL' => 'Sierra Leone',
            'SG' => 'Singapore',
            'SX' => 'Sint Maarten',
            'SK' => 'Slovakia',
            'SI' => 'Slovenia',
            'SB' => 'Solomon Islands',
            'SO' => 'Somalia',
            'ZA' => 'South Africa',
            'KR' => 'South Korea',
            'SS' => 'South Sudan',
            'ES' => 'Spain',
            'LK' => 'Sri Lanka',
            'SD' => 'Sudan',
            'SR' => 'Suriname',
            'SJ' => 'Svalbard and Jan Mayen',
            'SZ' => 'Swaziland',
            'SE' => 'Sweden',
            'CH' => 'Switzerland',
            'SY' => 'Syria',
            'TW' => 'Taiwan',
            'TJ' => 'Tajikistan',
            'TZ' => 'Tanzania',
            'TH' => 'Thailand',
            'TG' => 'Togo',
            'TK' => 'Tokelau',
            'TO' => 'Tonga',
            'TT' => 'Trinidad and Tobago',
            'TN' => 'Tunisia',
            'TR' => 'Turkey',
            'TM' => 'Turkmenistan',
            'TC' => 'Turks and Caicos Islands',
            'TV' => 'Tuvalu',
            'VI' => 'U.S. Virgin Islands',
            'UG' => 'Uganda',
            'UA' => 'Ukraine',
            'AE' => 'United Arab Emirates',
            'GB' => 'United Kingdom',
            'US' => 'United States',
            'UY' => 'Uruguay',
            'UZ' => 'Uzbekistan',
            'VU' => 'Vanuatu',
            'VA' => 'Vatican',
            'VE' => 'Venezuela',
            'VN' => 'Vietnam',
            'WF' => 'Wallis and Futuna',
            'EH' => 'Western Sahara',
            'YE' => 'Yemen',
            'ZM' => 'Zambia',
            'ZW' => 'Zimbabwe',
        ];
    }
}