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

function moesec_brute_force_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_brute_force_protection']) && check_admin_referer('moesec_brute_force_protection', 'moesec_brute_force_protection_nonce')) {
        $enable_captcha = isset($_POST['enable_captcha']) ? 1 : 0;
        $captcha_type = isset($_POST['captcha_type']) ? sanitize_text_field($_POST['captcha_type']) : 'recaptcha';
        $captcha_site_key = isset($_POST['captcha_site_key']) ? sanitize_text_field($_POST['captcha_site_key']) : '';
        $captcha_secret_key = isset($_POST['captcha_secret_key']) ? sanitize_text_field($_POST['captcha_secret_key']) : '';

        update_option('moesec_enable_captcha', $enable_captcha);
        update_option('moesec_captcha_type', $captcha_type);
        update_option('moesec_captcha_site_key', $captcha_site_key);
        update_option('moesec_captcha_secret_key', $captcha_secret_key);
        
        echo '<div class="updated"><p>' . esc_html__('Brute force protection settings saved successfully.', 'moesec') . '</p></div>';
    }
    
    $enable_captcha = get_option('moesec_enable_captcha', false);
    $captcha_type = get_option('moesec_captcha_type', 'recaptcha');
    $captcha_site_key = get_option('moesec_captcha_site_key', '');
    $captcha_secret_key = get_option('moesec_captcha_secret_key', '');
    
    ?>
    <h3><?php esc_html_e('Brute Force Protection', 'moesec'); ?></h3>
    <form method="post" action="">
        <?php wp_nonce_field('moesec_brute_force_protection', 'moesec_brute_force_protection_nonce'); ?>
        <table class="form-table">
            <tr>
                <th><label for="enable_captcha"><?php esc_html_e('Enable CAPTCHA', 'moesec'); ?></label></th>
                <td><input type="checkbox" id="enable_captcha" name="enable_captcha" <?php checked($enable_captcha); ?>></td>
            </tr>
            <tr>
                <th><label for="captcha_type"><?php esc_html_e('CAPTCHA Type', 'moesec'); ?></label></th>
                <td>
                    <select id="captcha_type" name="captcha_type">
                        <option value="recaptcha" <?php selected($captcha_type, 'recaptcha'); ?>><?php esc_html_e('reCAPTCHA', 'moesec'); ?></option>
                        <option value="hcaptcha" <?php selected($captcha_type, 'hcaptcha'); ?>><?php esc_html_e('hCaptcha', 'moesec'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="captcha_site_key"><?php esc_html_e('Site Key', 'moesec'); ?></label></th>
                <td><input type="text" id="captcha_site_key" name="captcha_site_key" value="<?php echo esc_attr($captcha_site_key); ?>" class="regular-text"></td>
            </tr>
            <tr>
                <th><label for="captcha_secret_key"><?php esc_html_e('Secret Key', 'moesec'); ?></label></th>
                <td><input type="text" id="captcha_secret_key" name="captcha_secret_key" value="<?php echo esc_attr($captcha_secret_key); ?>" class="regular-text"></td>
            </tr>
        </table>
        <p class="submit">
            <input type="submit" name="moesec_save_brute_force_protection" class="button button-primary" value="<?php esc_attr_e('Save Brute Force Protection Settings', 'moesec'); ?>">
        </p>
    </form>
    <?php
}

if (get_option('moesec_enable_captcha', false)) {
    add_action('login_enqueue_scripts', 'moesec_enqueue_captcha_scripts');
    add_action('login_form', 'moesec_add_captcha_to_login');
    add_filter('authenticate', 'moesec_verify_captcha', 20, 3);
}

function moesec_enqueue_captcha_scripts() {
    $captcha_type = get_option('moesec_captcha_type', 'recaptcha');
    
    if ($captcha_type === 'recaptcha') {
        wp_enqueue_script('recaptcha', 'https://www.google.com/recaptcha/api.js', array(), null, true);
    } elseif ($captcha_type === 'hcaptcha') {
        wp_enqueue_script('hcaptcha', 'https://js.hcaptcha.com/1/api.js', array(), null, true);
    }
}

function moesec_add_captcha_to_login() {
    $captcha_type = get_option('moesec_captcha_type', 'recaptcha');
    $site_key = get_option('moesec_captcha_site_key', '');
    
    if ($captcha_type === 'recaptcha') {
        echo '<div class="g-recaptcha" data-sitekey="' . esc_attr($site_key) . '"></div>';
    } elseif ($captcha_type === 'hcaptcha') {
        echo '<div class="h-captcha" data-sitekey="' . esc_attr($site_key) . '"></div>';
    }
}

function moesec_verify_captcha($user, $username, $password) {
    if (empty($username) || empty($password)) {
        return $user;
    }
    
    $captcha_type = get_option('moesec_captcha_type', 'recaptcha');
    $secret_key = get_option('moesec_captcha_secret_key', '');
    
    if ($captcha_type === 'recaptcha') {
        $captcha_response = isset($_POST['g-recaptcha-response']) ? sanitize_text_field($_POST['g-recaptcha-response']) : '';
        $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    } elseif ($captcha_type === 'hcaptcha') {
        $captcha_response = isset($_POST['h-captcha-response']) ? sanitize_text_field($_POST['h-captcha-response']) : '';
        $verify_url = 'https://hcaptcha.com/siteverify';
    } else {
        return $user;
    }
    
    $response = wp_safe_remote_post($verify_url, array(
        'body' => array(
            'secret' => $secret_key,
            'response' => $captcha_response
        )
    ));
    
    if (is_wp_error($response)) {
        return $user;
    }
    
    $body = wp_remote_retrieve_body($response);
    $result = json_decode($body, true);
    
    if (!$result['success']) {
        return new WP_Error('captcha_error', esc_html__('CAPTCHA verification failed. Please try again.', 'moesec'));
    }
    
    return $user;
}
