<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

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

    if (isset($_POST['moesec_save_login_protection']) && check_admin_referer('moesec_login_protection', 'moesec_login_protection_nonce')) {
        $login_attempts = isset($_POST['login_attempts']) ? absint($_POST['login_attempts']) : 3;
        $lockout_duration = isset($_POST['lockout_duration']) ? absint($_POST['lockout_duration']) : 30;
        $enable_2fa = isset($_POST['enable_2fa']) ? 1 : 0;

        update_option('moesec_login_attempts', $login_attempts);
        update_option('moesec_lockout_duration', $lockout_duration);
        update_option('moesec_enable_2fa', $enable_2fa);
        
        echo '<div class="updated"><p>' . esc_html__('Login protection settings saved successfully.', 'moesec') . '</p></div>';
    }
    
    $login_attempts = get_option('moesec_login_attempts', 3);
    $lockout_duration = get_option('moesec_lockout_duration', 30);
    $enable_2fa = get_option('moesec_enable_2fa', false);
    
    ?>
    <h3><?php esc_html_e('Login Protection', 'moesec'); ?></h3>
    <form method="post" action="">
        <?php wp_nonce_field('moesec_login_protection', 'moesec_login_protection_nonce'); ?>
        <table class="form-table">
            <tr>
                <th><label for="login_attempts"><?php esc_html_e('Max Login Attempts', 'moesec'); ?></label></th>
                <td>
                    <input type="number" id="login_attempts" name="login_attempts" value="<?php echo esc_attr($login_attempts); ?>" min="1">
                    <p class="description"><?php esc_html_e('Maximum number of failed login attempts before lockout.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="lockout_duration"><?php esc_html_e('Lockout Duration (minutes)', 'moesec'); ?></label></th>
                <td>
                    <input type="number" id="lockout_duration" name="lockout_duration" value="<?php echo esc_attr($lockout_duration); ?>" min="1">
                    <p class="description"><?php esc_html_e('How long to lock out an IP address after failed login attempts.', 'moesec'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="enable_2fa"><?php esc_html_e('Enable Two-Factor Authentication', 'moesec'); ?></label></th>
                <td>
                    <input type="checkbox" id="enable_2fa" name="enable_2fa" <?php checked($enable_2fa); ?>>
                    <p class="description"><?php esc_html_e('Enable 2FA globally. Users can configure their preferred method in their profile settings.', 'moesec'); ?></p>
                </td>
            </tr>
        </table>
        <p class="submit">
            <input type="submit" name="moesec_save_login_protection" class="button button-primary" value="<?php esc_attr_e('Save Login Protection Settings', 'moesec'); ?>">
        </p>
    </form>
    
    <?php if ($enable_2fa): ?>
    <div class="notice notice-info">
        <p>
            <strong><?php esc_html_e('Two-Factor Authentication is enabled!', 'moesec'); ?></strong><br>
            <?php esc_html_e('Users can now configure their 2FA settings in their WordPress profile page.', 'moesec'); ?>
        </p>
    </div>
    <?php endif; ?>
    <?php
}

add_filter('authenticate', 'moesec_check_login_attempts', 30, 5);

function moesec_check_login_attempts($user, $username, $password) {
    if (empty($username) || empty($password)) {
        return $user;
    }
    
    $ip_address = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '';
    $login_attempts = get_transient('moesec_failed_login_' . $ip_address);
    $max_attempts = get_option('moesec_login_attempts', 3);
    
    if ($login_attempts && isset($login_attempts['attempts']) && $login_attempts['attempts'] >= $max_attempts) {
        $lockout_duration = get_option('moesec_lockout_duration', 30) * 60;
        $time_left = $lockout_duration - (time() - $login_attempts['last_attempt']);
        
        if ($time_left > 0) {
            if (function_exists('moesec_log')) {
                moesec_log(sprintf('Login attempt blocked due to lockout: %s (IP: %s)', sanitize_user($username), $ip_address));
            }
            return new WP_Error('locked_out', sprintf(
                esc_html__('Too many failed login attempts. Please try again in %d minutes.', 'moesec'),
                ceil($time_left / 60)
            ));
        } else {
            delete_transient('moesec_failed_login_' . $ip_address);
        }
    }
    
    return $user;
}

// Track failed logins
add_action('wp_login_failed', 'moesec_failed_login');

function moesec_failed_login($username) {
    $ip_address = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '';
    $login_attempts = get_transient('moesec_failed_login_' . $ip_address);
    
    if (!$login_attempts || !is_array($login_attempts)) {
        $login_attempts = array(
            'attempts' => 1,
            'last_attempt' => time()
        );
    } else {
        $login_attempts['attempts']++;
        $login_attempts['last_attempt'] = time();
    }
    
    set_transient('moesec_failed_login_' . $ip_address, $login_attempts, get_option('moesec_lockout_duration', 30) * 60);
    
    if (function_exists('moesec_log')) {
        moesec_log(sprintf('Failed login attempt: %s (IP: %s, Attempt: %d)', sanitize_user($username), $ip_address, $login_attempts['attempts']));
    }
    
    if (function_exists('moesec_login_attempt_notification')) {
        moesec_login_attempt_notification(sanitize_user($username), $ip_address, 'Failed');
    }
}

// Clear failed attempts on successful login
add_action('wp_login', 'moesec_successful_login_clear_attempts', 10, 2);

function moesec_successful_login_clear_attempts($username, $user) {
    $ip_address = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '';
    delete_transient('moesec_failed_login_' . $ip_address);
    
    if (function_exists('moesec_log')) {
        moesec_log(sprintf('Successful login: %s (IP: %s)', sanitize_user($username), $ip_address));
    }
}
