<?php
/**
 * Firewall tab: active IP blocks + manual block + whitelist editor.
 *
 * @package Brainwerk Security Suite
 */

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

if ( ! empty( $_POST['shieldforge_firewall_action'] ) && check_admin_referer( 'shieldforge_firewall' ) && current_user_can( Shieldforge_Admin::CAP ) ) {
    $action = sanitize_key( wp_unslash( $_POST['shieldforge_firewall_action'] ) );
    if ( 'add_block' === $action ) {
        $ip      = sanitize_text_field( wp_unslash( $_POST['ip'] ?? '' ) );
        $minutes = max( 1, absint( wp_unslash( $_POST['minutes'] ?? 60 ) ) );
        $reason  = sanitize_text_field( wp_unslash( $_POST['reason'] ?? 'manual' ) );
        if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) {
            Shieldforge_Bruteforce::block_ip( $ip, $minutes, $reason );
            add_settings_error( 'brainwerk-security-suite', 'sf_blocked', sprintf( __( 'IP %s blocked for %d minutes.', 'brainwerk-security-suite' ), $ip, $minutes ), 'updated' );
        }
    }
}

global $wpdb;
$blocks_table = Shieldforge_Utils::table( 'blocks' );
$blocks       = Shieldforge_Bruteforce::active_blocks();
$whitelist    = (array) Shieldforge_Settings::get( 'bruteforce_whitelist', array() );
?>
<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Active blocks', 'brainwerk-security-suite' ); ?></h2>
    <?php if ( empty( $blocks ) ) : ?>
        <div class="sf-empty-state">
            <div class="sf-empty-icon dashicons dashicons-shield-alt"></div>
            <h3><?php esc_html_e( 'No active IP blocks.', 'brainwerk-security-suite' ); ?></h3>
            <p><?php esc_html_e( 'Either nobody has tripped your brute-force threshold, or every block has expired. The Logs tab shows historic blocks with one-click "Block this IP again" actions if you need them.', 'brainwerk-security-suite' ); ?></p>
            <a href="<?php echo esc_url( Shieldforge_Admin::tab_url( 'logs' ) ); ?>" class="button"><?php esc_html_e( 'Open Logs', 'brainwerk-security-suite' ); ?></a>
        </div>
    <?php else : ?>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'IP', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Reason', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Until (UTC)', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Actions', 'brainwerk-security-suite' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $blocks as $b ) : ?>
                    <tr>
                        <td><code><?php echo esc_html( $b->ip ); ?></code></td>
                        <td><?php echo esc_html( $b->reason ); ?></td>
                        <td><?php echo esc_html( $b->blocked_until ); ?></td>
                        <td>
                            <button class="button button-small sf-quick-unblock" data-ip="<?php echo esc_attr( $b->ip ); ?>">
                                <?php esc_html_e( 'Unblock', 'brainwerk-security-suite' ); ?>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Add manual block', 'brainwerk-security-suite' ); ?></h2>
    <form method="post" class="shieldforge-form">
        <?php wp_nonce_field( 'shieldforge_firewall' ); ?>
        <input type="hidden" name="shieldforge_firewall_action" value="add_block">
        <p>
            <label>
                <?php esc_html_e( 'IP address', 'brainwerk-security-suite' ); ?>
                <input type="text" name="ip" placeholder="203.0.113.42" required>
            </label>
            <label>
                <?php esc_html_e( 'Minutes', 'brainwerk-security-suite' ); ?>
                <input type="number" name="minutes" value="60" min="1" max="525600">
            </label>
            <label>
                <?php esc_html_e( 'Reason', 'brainwerk-security-suite' ); ?>
                <input type="text" name="reason" placeholder="manual">
            </label>
        </p>
        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Block IP', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Crawler & traffic rate limiting', 'brainwerk-security-suite' ); ?></h2>
    <p class="description">
        <?php esc_html_e( 'Throttles anonymous clients that exceed a requests-per-minute budget (HTTP 429; repeated offenders are banned). Genuine search engines (Google, Bing, Apple, Yandex, Baidu) are verified via reverse DNS and never throttled — clients faking a search-engine identity can be blocked outright. Logged-in users and whitelisted IPs are always exempt.', 'brainwerk-security-suite' ); ?>
    </p>
    <form method="post" action="">
        <?php wp_nonce_field( Shieldforge_Admin::NONCE ); ?>
        <input type="hidden" name="shieldforge_action" value="save_settings">
        <?php foreach ( array( 'ratelimit_enabled', 'ratelimit_verify_bots', 'ratelimit_block_fake_bots', 'ratelimit_rpm', 'ratelimit_crawler_rpm', 'ratelimit_ban_minutes' ) as $sf_rl_key ) : ?>
            <input type="hidden" name="shieldforge_tab_keys[]" value="<?php echo esc_attr( $sf_rl_key ); ?>">
        <?php endforeach; ?>
        <table class="form-table" role="presentation">
            <tr>
                <th scope="row"><?php esc_html_e( 'Enable rate limiting', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="shieldforge[ratelimit_enabled]" value="1" <?php checked( (bool) Shieldforge_Settings::get( 'ratelimit_enabled', false ) ); ?>>
                        <?php esc_html_e( 'Count anonymous front-end requests per IP and throttle clients above the limits', 'brainwerk-security-suite' ); ?>
                    </label>
                    <p class="description"><?php esc_html_e( 'Counters live in short-lived transients keyed by an IP hash — no plain-text IPs, no extra tables. On high-traffic sites a persistent object cache is recommended.', 'brainwerk-security-suite' ); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Limit for visitors (requests/min)', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <input type="number" name="shieldforge[ratelimit_rpm]" value="<?php echo esc_attr( max( 1, (int) Shieldforge_Settings::get( 'ratelimit_rpm', 240 ) ) ); ?>" min="1" max="100000" class="small-text">
                    <p class="description"><?php esc_html_e( 'A human barely exceeds 60 page views per minute; 240 leaves generous headroom for prefetching and asset-generating plugins.', 'brainwerk-security-suite' ); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Limit for crawlers (requests/min)', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <input type="number" name="shieldforge[ratelimit_crawler_rpm]" value="<?php echo esc_attr( max( 1, (int) Shieldforge_Settings::get( 'ratelimit_crawler_rpm', 60 ) ) ); ?>" min="1" max="100000" class="small-text">
                    <p class="description"><?php esc_html_e( 'Applies to clients whose user agent identifies as a bot/crawler/script. Verified search engines are exempt.', 'brainwerk-security-suite' ); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Ban duration (minutes)', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <input type="number" name="shieldforge[ratelimit_ban_minutes]" value="<?php echo esc_attr( max( 1, (int) Shieldforge_Settings::get( 'ratelimit_ban_minutes', 30 ) ) ); ?>" min="1" max="10080" class="small-text">
                    <p class="description"><?php esc_html_e( 'Applied after 3 limit violations within 15 minutes. The ban also appears under "Active blocks" above.', 'brainwerk-security-suite' ); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Search-engine verification', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="shieldforge[ratelimit_verify_bots]" value="1" <?php checked( (bool) Shieldforge_Settings::get( 'ratelimit_verify_bots', true ) ); ?>>
                        <?php esc_html_e( 'Verify claimed search-engine crawlers via reverse DNS (result cached for a week)', 'brainwerk-security-suite' ); ?>
                    </label>
                    <br>
                    <label>
                        <input type="checkbox" name="shieldforge[ratelimit_block_fake_bots]" value="1" <?php checked( (bool) Shieldforge_Settings::get( 'ratelimit_block_fake_bots', true ) ); ?>>
                        <?php esc_html_e( 'Block clients that fake a search-engine identity (403 + IP block)', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
        </table>
        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Save rate limiting', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Whitelist (CIDR or single IP, one per line)', 'brainwerk-security-suite' ); ?></h2>
    <form method="post" action="">
        <?php wp_nonce_field( Shieldforge_Admin::NONCE ); ?>
        <input type="hidden" name="shieldforge_action" value="save_settings">
        <input type="hidden" name="shieldforge_tab_keys[]" value="bruteforce_whitelist">
        <p>
            <textarea name="shieldforge[bruteforce_whitelist]" rows="6" class="large-text code" placeholder="10.0.0.0/8&#10;192.168.1.42"><?php echo esc_textarea( implode( "\n", $whitelist ) ); ?></textarea>
        </p>
        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Save whitelist', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>
