<?php
/*
Plugin Name: Guardify Firewall
Version: 1.1.2
Description: Advanced WordPress firewall with manual activation, 2FA, and GeoIP protection
Author: BitCleric
License: GPL-2.0+
*/

if (!defined('ABSPATH')) {
    exit;
}

define('GUARDIFY_PATH', plugin_dir_path(__FILE__));
define('GUARDIFY_URL', plugin_dir_url(__FILE__));
define('GUARDIFY_LOG_DIR', WP_CONTENT_DIR . '/guardify-logs');

// Include Google Authenticator library
require_once GUARDIFY_PATH . 'includes/GoogleAuthenticator.php'; // If added manually

// Include GeoIP class
require_once GUARDIFY_PATH . 'includes/geo.class.php';
require_once GUARDIFY_PATH . 'includes/class-guardify-firewall.php';
require_once GUARDIFY_PATH . 'includes/class-guardify-admin.php';

// Initialize WP_Filesystem
function guardify_init_filesystem() {
    if (!function_exists('WP_Filesystem')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    global $wp_filesystem;
    if (!WP_Filesystem()) {
        return false;
    }
    return $wp_filesystem;
}

function guardify_init() {
    $firewall = new Guardify_Firewall();
    $admin = new Guardify_Admin();
}
add_action('plugins_loaded', 'guardify_init');

function guardify_action_links($links) {
    $custom_links = array(
        '<a href="' . admin_url('admin.php?page=guardify-dashboard') . '">Dashboard</a>',
        '<a href="' . admin_url('admin.php?page=guardify-settings') . '">Settings</a>',
    );
    return array_merge($custom_links, $links);
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'guardify_action_links');

function guardify_activate() {
    $wp_filesystem = guardify_init_filesystem();
    if ($wp_filesystem === false) {
        return;
    }

    if (!$wp_filesystem->is_dir(GUARDIFY_LOG_DIR)) {
        $wp_filesystem->mkdir(GUARDIFY_LOG_DIR, 0755);
    }
    update_option('guardify_settings', ['enabled' => 0]);
}
register_activation_hook(__FILE__, 'guardify_activate');

function guardify_deactivate() {
    Guardify_Firewall::remove_ini();
}
register_deactivation_hook(__FILE__, 'guardify_deactivate');

function guardify_uninstall() {
    $wp_filesystem = guardify_init_filesystem();
    if ($wp_filesystem === false) {
        return;
    }

    delete_option('guardify_settings');
    delete_option('guardify_ip_rules');
    if ($wp_filesystem->is_dir(GUARDIFY_LOG_DIR)) {
        $files = $wp_filesystem->dirlist(GUARDIFY_LOG_DIR);
        if ($files) {
            foreach ($files as $file) {
                $wp_filesystem->delete(GUARDIFY_LOG_DIR . '/' . $file['name']);
            }
        }
        $wp_filesystem->rmdir(GUARDIFY_LOG_DIR);
    }
}
register_uninstall_hook(__FILE__, 'guardify_uninstall');

// 2FA Logic with Google Authenticator
function guardify_2fa_login($user, $password) {
    if (is_wp_error($user)) {
        return $user;
    }
    $settings = get_option('guardify_settings', []);
    if (!empty($settings['enable_2fa']) && in_array('administrator', $user->roles)) {
        // Verify nonce for 2FA submission
        if (!isset($_POST['guardify_2fa_nonce']) || !wp_verify_nonce($_POST['guardify_2fa_nonce'], 'guardify_2fa_login')) {
            return new WP_Error('invalid_nonce', esc_html__('Security check failed. Please try again.', 'guardify'));
        }

        $code = sanitize_text_field(wp_unslash($_POST['guardify_2fa_code'] ?? ''));
        $ga = new PHPGangsta_GoogleAuthenticator();
        $secret = get_user_meta($user->ID, 'guardify_2fa_secret', true);
        if (empty($secret)) {
            return new WP_Error('2fa_not_setup', esc_html__('2FA is enabled but not set up. Please configure it in your profile.', 'guardify'));
        }
        if (empty($code) || !$ga->verifyCode($secret, $code, 2)) { // 2 = 2*30sec tolerance
            return new WP_Error('invalid_2fa', esc_html__('Invalid 2FA code.', 'guardify'));
        }
    }
    return $user;
}
add_filter('authenticate', 'guardify_2fa_login', 30, 3);

function guardify_login_form_2fa() {
    $settings = get_option('guardify_settings', []);
    if (!empty($settings['enable_2fa'])) {
        // Add nonce field for 2FA submission
        wp_nonce_field('guardify_2fa_login', 'guardify_2fa_nonce');
        echo '<p><label for="guardify_2fa_code">' . esc_html__('2FA Code', 'guardify') . '</label>';
        echo '<input type="text" name="guardify_2fa_code" id="guardify_2fa_code" class="input" value="" size="20" /></p>';
    }
}
add_action('login_form', 'guardify_login_form_2fa');

// Add 2FA setup to user profile
function guardify_profile_2fa_fields($user) {
    $settings = get_option('guardify_settings', []);
    if (empty($settings['enable_2fa']) || !in_array('administrator', $user->roles)) {
        return;
    }

    $ga = new PHPGangsta_GoogleAuthenticator();
    $secret = get_user_meta($user->ID, 'guardify_2fa_secret', true);
    if (empty($secret)) {
        $secret = $ga->createSecret();
        update_user_meta($user->ID, 'guardify_2fa_secret', $secret);
    }

    $qrCodeUrl = $ga->getQRCodeGoogleUrl(get_bloginfo('name') . ':' . $user->user_login, $secret);
    ?>
    <h3><?php esc_html_e('Two-Factor Authentication (2FA)', 'guardify'); ?></h3>
    <table class="form-table">
        <tr>
            <th><label><?php esc_html_e('2FA Secret Key', 'guardify'); ?></label></th>
            <td>
                <input type="text" value="<?php echo esc_attr($secret); ?>" readonly class="regular-text">
                <p class="description"><?php esc_html_e('This is your 2FA secret key. Keep it safe and do not share it with anyone.', 'guardify'); ?></p>
            </td>
        </tr>
        <tr>
            <th><label><?php esc_html_e('QR Code', 'guardify'); ?></label></th>
            <td>
                <img src="<?php echo esc_url($qrCodeUrl); ?>" alt="QR Code">
                <p class="description"><?php esc_html_e('Scan this QR code with Google Authenticator to set up 2FA.', 'guardify'); ?></p>
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'guardify_profile_2fa_fields');
add_action('edit_user_profile', 'guardify_profile_2fa_fields');